Node.js - How to write file in Node.js using fs module

Node.js - How to write file in Node.js using fs module

Node.js

Share

In this tutorial we will learn to write data in file in Node.js using fs module.

The fs module

The fs module helps in interacting with the file system and provides operations that are available in synchronous, callback and promise-based forms.

Read the following tutorial to learn How to read file in Node.js using fs module.

Write data in file synchronously

To write data in file in sync mode we use the writeFileSync method.

The writeFileSync takes three parameters.

  • file - This is the path of the file in which we write the data.
  • data - This is the data that we want to write.
  • options - This take encoding (like utf8)
const fs = require('fs');

const file = '/Users/yusufshakeel/node-project/example.txt';

console.log('Writing file');

fs.writeFileSync(file, 'Hello World', 'utf8');

console.log('Writing done!');

In the above code we are writing the content Hello World to file example.txt using utf8 encoding.

The writeFileSync method returns undefined.

Let's try to modify the above code to also read the content that we wrote in the file.

const fs = require('fs');

const file = '/Users/yusufshakeel/node-project/example.txt';

console.log('Writing file');

fs.writeFileSync(file, 'Hello World', 'utf8');

console.log('Writing done!');


console.log('Reading content:');

const content = fs.readFileSync(file, 'utf8');
console.log(content);

console.log('Reading done!');

Output:

Writing file
Writing done!
Reading content:
Hello World
Reading done!

Error handling

To catch error for the above code we can wrap it in try-catch block like the following.

The following code will throw error.

const fs = require('fs');

try {
    const file = '/Users/yusufshakeel/node-project/example.txt';

    console.log('Writing file');

    fs.writeFileSync(file, {}, 'utf8');

    console.log('Writing done!');


    console.log('Reading content:');

    const content = fs.readFileSync(file, 'utf8');
    console.log(content);

    console.log('Reading done!');

} catch (e) {
    console.log('ERROR:');
    console.log(e.message);
}

Output:

Writing file
ERROR:
The "data" argument must be of type string or an instance of Buffer, TypedArray, or DataView. Received an instance of Object

Write data asynchronously

To write data asynchronously we use the writeFile method.

It takes four parameters.

  • file - This is the path of the file in which we write the data.
  • data - This is the data that we want to write.
  • options - This take encoding (like utf8)
  • callback - This is the callback function which has error parameter.

In the following code we are writing data asynchronously.

const fs = require('fs');

const file = '/Users/yusufshakeel/node-project/example.txt';

console.log('Writing file');

fs.writeFile(file, 'Hello World', 'utf8', err => {
    if (err) {
        console.log('ERROR:')
        console.log(err.message);
    } else {
        console.log('Writing done!');

        console.log('Reading content:');
        const content = fs.readFileSync(file, 'utf8');
        console.log(content);
        console.log('Reading done!');
    }
});

Output

Writing file
Writing done!
Reading content:
Hello World

In the above code we are writing Hello World in utf8 encoding inside example.txt file. If there is no error and the writing is done then the else block will get executed.

If any error is present in the err parameter then the if block will get executed which will console log the error message.

Write data in file using promise

The fs.promises API provides async file system methods that returns Promise object rather than callbacks.

So, when the promise gets resolved the code inside the then block will be executed. If error occurs then catch block will be executed.

const fs = require('fs').promises;

const file = '/Users/yusufshakeel/node-project/example.txt';

fs.writeFile(file, 'Hello World', 'utf8')
  .then(err => {
    console.log('Writing done!');
  })
  .catch(err => {
    console.log('ERROR:');
    console.log(err.message);
  });

Let's modify the above code to also print the content that was written in the file.

const fs = require('fs').promises;

const file = '/Users/yusufshakeel/node-project/example.txt';

fs.writeFile(file, 'Hello World', 'utf8')
  .then(err => {
    console.log('Writing done!');
  })
  .then(() => fs.readFile(file, 'utf8'))
  .then(data => {
    console.log('Content:');
    console.log(data);
  })
  .catch(err => {
    console.log('ERROR:');
    console.log(err.message);
  });

In the above code we will first write the content in the file. Once the writing completes the first then block will be executed and it will console log Writing done!.

After that the second then block is executed. Inside it we are reading the content of the file using readFile which is async. So, we will process it in the third then block.

Once the readFile is done reading and the promise is resolved the third then block will be executed. It will console log the content of the file.

In case writeFile or readFile promise gets rejected then the catch block will be considered and the code inside it will be executed.

Alright, this brings us to the end of this tutorial. Don't forget to practice. Thanks for reading. Please share if this was helpful. See you in the next tutorial.

Share