Re: How to pass/get fileName in callBack of watchFile

48 views
Skip to first unread message

Anirban Bhattacharya

unread,
Nov 25, 2015, 8:48:17 PM11/25/15
to nodejs, Anirban Bhattacharya, Anirban Bhattacharya
I also Tried the below option

for(i=0;i<fileNames.length;i++)
{
console.log(fileNames[i]);
fs.watchFile(fileNames[i],function(prev,cur){
console.log(fileNames[i]);
doAll(fileNames[i]);
});
}
function doAll(fileName)
{

console.log(fileName);
}

But the console.log() in callback printing undefined.
--------------------------------------------
On Tue, 24/11/15, Anirban Bhattacharya <anirbanbhat...@gmail.com> wrote:

Subject: How to pass/get fileName in callBack of watchFile
To: "nodejs" <nod...@googlegroups.com>
Cc: "Anirban Bhattacharya" <anirbanbhat...@yahoo.co.in>
Date: Tuesday, 24 November, 2015, 10:22 AM

HI,

I have to watch multiple files, and I don't want to
create seperate callback function for each.

fs.watchFile(testFile,callBack);
function callBack(cur,prev) {
console.log("in Test..");
var data='';
}

How can I get the fileName from the callBack function?

Thanks,
Anirban

Anirban Bhattacharya

unread,
Nov 25, 2015, 8:48:17 PM11/25/15
to nodejs, Anirban Bhattacharya

Jimb Esser

unread,
Dec 10, 2015, 7:51:16 PM12/10/15
to nodejs, anirbanbhat...@gmail.com, anirbanbhat...@yahoo.co.in
The parameters passed to your callback are fs.Stats objects, which unfortunately do not contain a filename, so you need to pass one along yourself.  Your second approach was the right idea, but implemented with a common asynchronous code bug - by the time your callback is called, i is now equal to fileNames.length, so fileNames[i] is undefined.  You probably want something which binds the filename to your callback:
  for (i=0; i<fileNames.length; i++) {
    fs.watchFile(filename, doAll.bind(null, fileNames[i]));
  }
or creates a new scope for every step of the loop:
  fileNames.forEach(function(filename) {
    fs.watchFile(filename, function() {
      doAll(filename);
    });
  });
Reply all
Reply to author
Forward
0 new messages