Javascript Node.js如何从$http调用关闭fs.close
我已经挣扎了很多天来开始和停止文件读取。我有两个按钮在我的角度html页面。一个是开始,一个是停止文件读取过程。文件读取代码在“开始”按钮上工作,但“停止”按钮不工作。不知道怎么做。请给我提个建议Javascript Node.js如何从$http调用关闭fs.close,javascript,jquery,angularjs,node.js,Javascript,Jquery,Angularjs,Node.js,我已经挣扎了很多天来开始和停止文件读取。我有两个按钮在我的角度html页面。一个是开始,一个是停止文件读取过程。文件读取代码在“开始”按钮上工作,但“停止”按钮不工作。不知道怎么做。请给我提个建议 <button id="starttodb" style="margin-left:25px;margin-right:25px;" ng-click="starttodb()">starttodb</button> <button id="stoptodb" style
<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>
调用此文件读取路由函数中的代码
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)
然后是停止文件(您需要访问watchers变量,因此您需要将两个路由放在同一个文件中,或者将此变量放在单独的包中,并将其导入两个路由文件中)
如果只有一个客户机,则忽略开始文件和停止文件使用中的watchers变量:
fs.unwatchFile(req.body.filename);
非常感谢@Valera的及时回复。我非常感激。我会检查并很快接受答案。它起作用了。我将开始和停止路由放在同一个文件中,并引用相同的文件名来停止路由。
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);