Home > database >  Nodejs fs.watch / fs.readFile - return added file
Nodejs fs.watch / fs.readFile - return added file

Time:11-06

I need to watch a folder where i write files to. When a new file is added, i want to know which one is it, and then return it somewhere else in my application I have tried using fs.watch() and chokidar and it works. My issue, is that i can't seem to be able to return the added file, it always comes as 'undefined'. I tried to find a way pass 'data' outside and return it there, but i couldn't

const readFromFile = () => {
  console.log("waiting for new message...")
  fs.watch('./db', (eventType, filename) => {
    if (filename) {
      fs.readFile(`./db/${filename}`, 'utf-8', (err, data) => {
        if (err) throw err;
        //console.log(data); <-- prints new file added
        return data;  <-- returns undefined
      });
    }});
} 

I need to acces the added file from another part of the application, so i can process it further.

const file = readFromFile();
console.log(file); <-- undefined

Can someone suggest any refactoring i need to do?

CodePudding user response:

You can provide a callback function to be invoked whenever a file was read:

const readFromFile = (cb) => {
  fs.watch('./db', (eventType, filename) => {
    if (filename) {
      fs.readFile(`./db/${filename}`, 'utf-8', (err, data) => {
        if (err) throw err;
        cb(data); 
      });
    }});
} 

And then use it like:

readFromFile((data) => console.log(data));
  • Related