javascript - How can I identify when a copy process in node.js is finished? -
this first steps node.js. watch directory chokidar added files. if copy process finished script should called. don't know how can identify when copy process finished , file complete available on directory. console log command word finish never appear.
var fs = require('fs'); var chokidar = require('chokidar'); var watcher = chokidar.watch('/root/documents/gw/', {ignored: /^\./, persistent: true}); watcher .on('add', function(path) { console.log('file', path, 'has been added'); fs.watchfile(path, function(curr, prev) { if (curr.size == prev.size) { console.log('finish'); // todo start shell script } else { console.log(curr.size); } }); });
i use node.js version 0.10.25 on linux system.
thanks in advance help!
the reason test never positive on simple copy operation fs.watchfile
won't generate event previous size going equal current size. happen, there have change file, because fs.watchfile
fire on changes. in straightforward copy operation there typically won't file change occurring previous size , current size same.
here's solution detects when file has stopped changing after set timeout:
var fs = require('fs'); var chokidar = require('chokidar'); var watcher = chokidar.watch('dir', {ignored: /^\./, persistent: true}); var end_timeout = 30000; watcher .on('add', function(path) { console.log('file', path, 'has been added'); fs.stat(path, function (err, stat) { // replace error checking appropriate app. if (err) throw err; settimeout(checkend, end_timeout, path, stat); }); }); function checkend(path, prev) { fs.stat(path, function (err, stat) { // replace error checking appropriate app. if (err) throw err; if (stat.mtime.gettime() === prev.mtime.gettime()) { console.log("finished"); // move on: call whatever needs called process file. } else settimeout(checkend, end_timeout, path, stat); }); }
note if directory prepopulated files, code start watching them right away. can imagine use-case scenarios desirable , not.
Comments
Post a Comment