Example: How to Read and Write files using Node.js

09.08.2019

Example: How to Read and Write files using Node.js

In this example, we will go through how to read and write files using Node. Here we will go through using the synchronous and non-synchronous versions with a brief explanation of when to use each.

Setup

mkdir readWriteExample
cd readWriteExample
touch readWriteFile.js

Reading and Writing Synchronously

Let's start with syncronously writing to a file. s

// Include the built in file system library
const fs = require('fs');

// A path for the file in our current directory
const filePath = './example.txt';

// Use `sync` write file version
fs.writeFileSync(filePath, 'Example Text');

This will output Example Text to our example.txt file.

To read the contents, we can add the following.

const contents = fs.readFileSync(filePath, 'utf8');
console.log(contents);

Reading and Writing Asynchronously

The above is nice for running command line applications or devops scripts, but when we are working with an API we will want to use the async versions. In short, this is because Node is single threaded and IO operations like file reading/writing will block the thread. So, many of your users will be blocked by one user trying to read a file.

The only difference is we remove the Sync suffix and then we add a callback to the function call.

const fs = require('fs');

const filePath = './example.txt';

// Use `async` write file version
fs.writeFile(filePath, 'Example Text', (err) => {
  console.log(err);
});

// Using the async
fs.readFile(filePath, 'utf8', (err, data) => {
  console.log(contents);
});