Skip to main content

Reading and Writing Files

In Node.js, one of the core modules available is the File System (fs) module, which provides a wide range of functionalities to interact with the file system in your machine. With the fs module, you can read files, write files, watch files, and more. In this article, we will focus on reading and writing files using the fs module.

Importing fs Module

Before we can work with files in Node.js, we need to import the fs module. Here's how you do it:

const fs = require('fs');

With the fs module now available, we can start reading and writing files.

Reading Files

The fs module provides the readFile method to read files. This method is asynchronous, which means it won't block the rest of your code from executing while it reads the file.

Here's an example:

fs.readFile('test.txt', 'utf8', function(err, data){
if (err) throw err;
console.log(data);
});

In this example, 'test.txt' is the name of the file we want to read, 'utf8' is the character encoding of the file, and the function is a callback that will be called when the file has been read. The callback function takes two arguments: an error object, which will be non-null if there was an error, and the data from the file.

If you want to read a file synchronously, you can use the readFileSync method:

let data = fs.readFileSync('test.txt', 'utf8');
console.log(data);

With readFileSync, the method doesn't return until the file has been read, which means it will block the rest of your code.

Writing Files

The fs module also provides methods to write data to files. The writeFile method can be used to write data to a file. If the file does not exist, writeFile will create it:

fs.writeFile('test.txt', 'Hello, world!', function(err){
if (err) throw err;
console.log('File has been written');
});

In this example, 'test.txt' is the name of the file we want to write to, 'Hello, world!' is the data we want to write, and the function is a callback that will be called when the file has been written. The callback function takes one argument: an error object, which will be non-null if there was an error.

Just like with reading files, there's a synchronous method for writing files too, called writeFileSync:

fs.writeFileSync('test.txt', 'Hello, world!');
console.log('File has been written');

With writeFileSync, the method doesn't return until the file has been written, which means it will block the rest of your code.

Conclusion

The fs module in Node.js provides a powerful set of methods for interacting with the file system. In this article, we've only scratched the surface of what's possible. We've looked at how to read data from files and how to write data to files, both synchronously and asynchronously. With these basics down, you can start to explore the other capabilities of the fs module.