Home > Mobile >  Using fs.read inside promise does not work
Using fs.read inside promise does not work

Time:10-17

I am trying to do a fs.read after the promise job is done by using the .then()

Here is how my code looks like

(async () => {
    const feed = await parser.parseURL('https://www.nasa.gov/rss/dyn/breaking_news.rss');
    console.log(feed.title);
    const items = [];

    await Promise.all(feed.items.map(async (currentItem) => {

      // some code here to create data
      items.push(data);
    })).then(
      items.forEach((element) => {
        const file = downloadFile(element.url);

        let checksumValue;
        try {
          fs.readFileSync(file, (_err, data) => {
            checksumValue = generateChecksum(data);
            console.log(`The checksum is: ${checksumValue}`);
            // Delete the downloaded file
            deleteFile(file);
          });
        } catch (error) {
          console.error(error);
        // expected output: ReferenceError: nonExistentFunction is not defined
        // Note - error messages will vary depending on browse
        }
      })(),
    );
  })();

But it doesn't operate this piece of code :

fs.readFileSync(file, (_err, data) => {
            checksumValue = generateChecksum(data);
            console.log(`The checksum is: ${checksumValue}`);
            // Delete the downloaded file
            deleteFile(file);
          });

How should I read the file?

CodePudding user response:

fs.readFileSync is sync, so it doesn't take a callback.

Either use the non-sync version:

fs.readFile(file, (_err, data) => {
            checksumValue = generateChecksum(data);
            console.log(`The checksum is: ${checksumValue}`);
            // Delete the downloaded file
            deleteFile(file);
          });

or use it as intended:

const data = fs.readFileSync(file);
checksumValue = generateChecksum(data);
console.log(`The checksum is: ${checksumValue}`);
// Delete the downloaded file
deleteFile(file);
  • Related