My Development Notes

Programming Made Easier


NodeJS

How to Read and Write files using NodeJS?

First import the build-in file system module like so :

const fs = require('fs');

Synchronous Way

Now, in order to use the fs (file-system) module to read a file, use the following code syntax :

fs.readFileSync('<filePath>', 'utf-8');
// specify the location where the input file is located, utf-8 for English

Now if you log the file above to the console, it will read and display the suitable file.

Let’s now say you want to write a file in NodeJS, all you have to do is use the below code syntax :

fs.writeFileSync('<filePath>', outputTEXT);

The output will be suitably printed elsewhere wherever you want it coded.

All the codes are available under the File System module of the NodeJS documentation.

Asynchronous Way

Below is the asynchronous way to read file in NodeJS :

fs.readFile('<filePath>', 'utf-8', (err, data) => {
  console.log(data);
}
// here we have the file location and the callback function with error as the first parameter and data being the second, basically a callback function

Next, to write files asynchronously we’ll use the following code syntax :

fs.writeFile('<filePath>', 'utf-8', callbackFunction)

Posted

in

by

Tags:

Leave a Reply