Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Nodejs fs.watch / fs.readFile – return added file

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading