Junior Dev Blog

How to read and write to a file using Node.js

2022-08-18 at Nodejs category

The fs (file system) module


NOTE: Reading a file via fs module's readFile & readFileSync methods load all of the file content within system memory (RAM) which is fine for small sized files but when it comes to large files, it's not a optimal solution and could lead to poor performance or straight up server crashes.

A better approach is to use STREAMS


Within Nodejs, we have a module named fs which is responsible for handling filesystem actions such as reading, writing, checking for existance amoung other things

There are 2 major approaches to achieve both of the above tasks via fs which are async or sync

If you don't know what async or sync mean in Javascript, in short, async means that the code interpreter won't wait for you async function call to complete before moving down to other code, once that function call is done with the work, it will fire a callback function of your choice (we'll see how in just a min), sync means exactly the opposite, it will make the code wait for its completion before moving down.

Reading a file

Within the fs module, we have a method named readFile which accepts three arguments, filePath (string) , encoding type (string) such as 'utf8' and a callback funtion which itself has two arguments (error, data).

Take a look at the code below

For example, we have a file named test.txt and it has content

//text.txt file
Some demo content
const fs = require('fs');

fs.readFile('/Users/zulfiqar/test.txt', 'utf8', (err, data) => {
  if (err) {
    console.error(err);
    return;
  }
  console.log(data);
});

Output:
Some demo content

Doing the above task synchronously isn't too hard, we just use readFileSync method like below

const fs = require('fs');

try {
  const data = fs.readFileSync('/Users/zulfiqar/test.txt', 'utf8');
  console.log(data);
} catch (err) {
  console.error(err);
}

NOTE: If there's an error while reading a file with sync method, it will halt the whole program, to prevent this, we have to wrap this call in a try catch block

Writing to a file

As for writing to a file, we have an async method available on fs which is fs.writeFile Let's have a look at how it works

const fs = require('fs');

//contents to be written into a file
const content = 'Some content!';

fs.writeFile('/Users/zulfiqar/test.txt', content, err => {
  if (err) {
    console.error(err);
  }
  // file written successfully
});

As readFile, writeFile method also accepts three params, but they are a bit different, first one is the file path (which file to write to), note that if the file given doesn't exist, writeFile method will create it for you

Second argument is the actual content (string) which is to be written to a file

Lastly a callback function with an error, which could be null || undefined if there are no errors and file is successfully written to.

Doing this with its alternative sync method

const fs = require('fs');

const content = 'Some content!';

try {
  fs.writeFileSync('/Users/zulfiqar/test.txt', content);
  // file written successfully
} catch (err) {
  console.error(err);
}

That's pretty much it! Thanks for reading :)

Zulfiqar Ali

Personal blog by Zulfiqar Ali.

developer tutorial treats