Read files in Node.js


This article is a reminder of all the possibilities we have for reading files in Node.js. Some of the following options should look familiar, while others are brand new.


1 | fs.createReadStream()


// Example 1
const fs = require('fs');
const file = 'poem.txt';

const readStream = fs.createReadStream(file, 'utf-8');

readStream.on('data', (chunk) => {
  console.log(chunk);
});

This example was previously seen in chapter 7, except that there is one tiny variation. We set the format of the Readable Stream by passing a second argument 'utf-8' to the method fs.createReadStream().


2 | fs.readFile()


In this example, we use the non-blocking function fs.readFile() which is a single-event non-blocking option. Its last argument is an error-first callback function.


// Example 2
const fs = require('fs');
const file = 'poem.txt';

fs.readFile(file, 'utf8', (err, data) => {
  if (err) {
    throw err;
  } else {
  console.log(data);
  }
});

3 | fs.promises.readFile()


In Node.js 10 and later, the fs.promises object has a number of predefined Promise-based functions for working with the filesystem.


// Example 3a

const fs = require('fs');
const file = 'poem.txt';

const pReadFile_1 = (file) => {
  return fs.promises.readFile(file, 'utf-8');
}

pReadFile_1(file)
  .then((content) => console.log(content));

// Example 3b

const fs = require('fs');
const file = 'poem.txt';

const pReadFile_2 = file => fs.promises.readFile(file, 'utf-8');

pReadFile_2(file)
  .then((content) => console.log(content));

This example is similar to example 3a, except that we use a one-liner arrow function.


// Example 3c

const fs = require('fs');
const file = 'poem.txt';

const pReadFile_4 = async (file) => {
  return await fs.promises.readFile(file, 'utf-8');
}

pReadFile_4(file)
  .then((content) => console.log(content));

In this example, we use the async/await keywords.


// Example 3d

const fs = require('fs');
const file = 'poem.txt';

const pReadFile_3 = async file => await fs.promises.readFile(file, 'utf-8');

pReadFile_3(file)
  .then((content) => console.log(content));

In this example, we use the async/await keywords and a one-liner arrow function.


4 | util.promisify(fs.readfile)


Node.js also provides a wrapper, util.promisify, to create Promise-based variants of its callback-based functions.


// Example 4a

const util = require('util');
const fs = require('fs');
const upReadFile = util.promisify(fs.readFile);

const file = 'poem.txt';

const pReadFile_1 = (file) => {
  return upReadFile(file, 'utf-8');
}

pReadFile_1(file)
  .then((content) => console.log(content));

// Example 4b

const util = require('util');
const fs = require('fs');
const upReadFile = util.promisify(fs.readFile);

const file = 'poem.txt';

const pReadFile_2 = file => upReadFile(file, 'utf-8');

pReadFile_2(file)
  .then((content) => console.log(content));

// Example 4c

const util = require('util');
const fs = require('fs');
const upReadFile = util.promisify(fs.readFile);

const file = 'poem.txt';

const pReadFile_3 = async (file) => {
  return await upReadFile(file, 'utf-8');
}

pReadFile_3(file)
  .then((content) => console.log(content));

// Example 4d

const util = require('util');
const fs = require('fs');
const upReadFile = util.promisify(fs.readFile);

const file = 'poem.txt';

const pReadFile_4 = async file => await upReadFile(file, 'utf-8');

pReadFile_4(file)
  .then((content) => console.log(content));

5 | fs.readFileSync()


fs.readFileSync() is the blocking version ("synchronous") of fs.readFile().


// Example 5

const fs = require('fs');
const file = 'poem.txt';

const content = fs.readFileSync('poem.txt');

console.log(content);

6 | readline.createInterface() and fs.createReadStream()


The readline module provides an interface for reading data from a Readable stream one line at a time. Instances of the readline.Interface class are constructed using the readline.createInterface() method (note that the class and the constructor do not have the same name). Every instance is associated with a single input Readable Stream and an optional single output Writable Stream. The output stream is used to print prompts for user input that arrives on, and is read from, the input stream.


Instances of readline.Interface are Emitters. The most interesting event emitted by readline interfaces is the 'line' event.


// Example 6a

const fs = require('fs');
const readline = require('readline');
const file = 'poem.txt';

const lineInterface = readline.createInterface({
  input: fs.createReadStream(file),
  output: process.stdout
});

// Example 6b

const fs = require('fs');
const readline = require('readline');
const file = 'poem.txt';

const lineInterface = readline.createInterface({
  input: fs.createReadStream(file),
});

lineInterface.on('line', line => console.log(line));

Author:
Initial publication date:
Last updated: