我已经挣扎了很多天来开始和停止文件读取。我的 Angular html 页面中有两个按钮。一个用于启动,一个用于停止文件读取过程。文件读取代码在开始按钮上起作用,但停止按钮不起作用。不知道如何做到这一点。请给我建议一些东西。
<button id="starttodb" style="margin-left:25px;margin-right:25px;" ng-click="starttodb()">starttodb</button>
<button id="stoptodb" style="margin-left:25px;margin-right:25px;" ng-click="stoptodb()">stoptodb</button>
并且有两个功能与 Controller 中的这两个按钮相关联。
$scope.starttodb = function() {
var filename = 'D:\\test.txt'
$http({
url: '/starttodb',
method: "POST",
data: {filename: filename}
}).success(function (response) {
console.log("success in starttodb");
});
};
$scope.stoptodb = function() {
var filename = 'STOP'
$http({
url: '/starttodb',
method: "POST",
data: {filename: filename}
}).success(function (response) {
console.log("success in starttodb");
});
};
在路由函数中调用此文件读取代码。
var bite_size = 1024,readbytes = 0,file;
var filename = req.body.filename ;
var initcontent = fs.readFileSync(filename);
console.log('Initial File content : \n' + initcontent);
console.log('Initial File content length: \n' + initcontent.length);
readbytes = initcontent.length;
fs.watchFile(filename, function() {
fs.open(filename, "r", function(error, fd) {
fs.read(fd, new Buffer(bite_size), 0, bite_size, readbytes, function(err, bytecount, buff) {
console.log(buff.toString('utf-8', 0, bytecount));
console.log('File Changed ...'+fd);
readbytes+=bytecount;
});
});
})
我想在单击停止按钮时停止读取此文件。
提前致谢。
最佳答案
要停止文件读取,您需要取消监视该文件(如果您有多个客户端,则通过特定监听)
您的启动函数将如下所示:
// outside of the route
var watchers = []
// inside the route
var bite_size = 1024,readbytes = 0,file;
var filename = req.body.filename ;
var initcontent = fs.readFileSync(filename);
console.log('Initial File content : \n' + initcontent);
console.log('Initial File content length: \n' + initcontent.length);
readbytes = initcontent.length;
var watcherFunction = function() {
fs.open(filename, "r", function(error, fd) {
fs.read(fd, new Buffer(bite_size), 0, bite_size, readbytes, function(err, bytecount, buff) {
console.log(buff.toString('utf-8', 0, bytecount));
console.log('File Changed ...'+fd);
readbytes+=bytecount;
});
});
}
watchers.push({
client_id: some_client_id,
watcherFunction: watcherFunction
})
fs.watchFile(filename, watcherFunction)
然后是你的停止文件(你将需要访问观察者变量,因此你需要将两个路由放在同一个文件中,或者将此变量放在一个单独的包中并将其导入到两个路由文件中)
var clientWatcherIndex = watchers.findIndex(w => w.client_id === some_client_id)
var clientWatcher = watchers[clientWatcherIndex]
fs.unwatchFile(req.body.filename, clientWatcher.watcherFunction);
watchers.splice(clientWatcherIndex , 1); // remove the watcher from list
如果您只有一个客户端,则忽略启动文件中的观察者变量,并在停止文件中使用:
fs.unwatchFile(req.body.filename);
关于javascript - Node.js 如何从 Angular $http 调用 fs.close,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46349532/