0

I'm trying to solve this issue but I am stuck! the function should return some data after reading the file but I can not figure out how to do it. The function returns undefined instead of the corresponding data.

const fs = require('fs');
const path = require('path');
const { resolve } = require('path');

const findFile = (fileName) => {
  const filePath = path.join(__dirname, fileName);
  return fs.promises.readFile(filePath, { encoding: 'utf-8' });
};

const processDataFromFile = (inputFile) => {
  findFile(inputFile)
    .then((data) => {
      const dataProcessed = doSomeStuffWith(data); // do some stuff with data
      return dataProcessed;
    })
    .catch((err) => console.log(err));
};

console.log(processDataFromFile('fileToRead.txt')); // it should return the data instead of undefined

What am I doing wrong? What Javascript feature am I not aware of?

  • 2
    `processDataFromFile` doesn't have a `return` statement inside. You only have a `return` inside the callback given to `then`. You most likely simply need `return findFile(inputFile)` and to change the logging to `processDataFromFile('fileToRead.txt').then(console.log)` – VLAZ Jul 15 '20 at 20:20
  • If you add `return` you get a promise. This is expected, as you cannot expect to get a result *now* that is only available in some *future*. – trincot Jul 15 '20 at 20:22
  • I added `return findFile(inputFile) ` and it works! It returns a `Promise `, then I process the promise. Thank you @VLAZ! – Maira Diaz Marraffini Jul 15 '20 at 20:45

0 Answers0