Node.js read file using promise


Callback

Normally, fs.readFile is called with a callback:

const fs = require('fs');
const path = require('path');

const filepath = path.resolve(__dirname, 'file.txt');

fs.readFile(filepath, 'utf8', (error, data) => {
  console.log(data);
});

Promise

To call fs.promises.readFile using async/await:

const fs = require('fs');
const path = require('path');

const filepath = path.resolve(__dirname, 'file.txt');

(async () => {
  const data = await fs.promises.readFile(filepath, 'utf8');
  console.log(data);
})();


Please support this site and join our Discord!