DEV Community

Anirudh Sharma
Anirudh Sharma

Posted on

Read/Write Files In NodeJS

Hello fellow devs 👋! I am sure like me you find yourself in a position where you need to read from a file or write to a file in your day to day work.

In this post, we will understand and see the code snippets for these two tasks.

But how will we do that, you ask 🤔? Luckily for us, we have a File System (fs) module which is a part of the code library of Node JS.

One important thing, since it is a core module, we don’t have to install it explicitly. Cool, eh 😄?

Read From File

Reading from files is one of the most common things we do when we build an application using Node JS.

We can read files in two ways - asynchronous (non-blocking) and synchronous (blocking). Usually, the preferable way is non-blocking i.e., ask node to read a file, and then to get a callback when reading is finished.

Let's look at the code

// Import the module
const fs = require('fs');

// This function reads the file and prints the data on the
// console using the callback function
const readFile = () => {
    fs.readFile('files/sample-text-file.txt', 'utf8',
        (err, data) => {
            if (err) {
                return console.log(err);
            }
            console.log(data);
        });
}

module.exports = {
    readFile
};
Enter fullscreen mode Exit fullscreen mode

Here, we are passing the path of the file to be read and the type of encoding.

If we wish to read the file synchronously then we can use the function readFileSync instead of readFile.

Write To File

Like reading from a file, a common use case is to write into a file. We can leverage the core File System (fs) Node JS module.

Here also, like reading, we have two ways - asynchronous (non-blocking) and synchronous (blocking).

Let's see the code for writing to a file asynchronously.

// Import the core node js fs module
const fs = require('fs');
// The content to be written into the file
const content = 'This content will be written into the file';

const writeFile = () => {
    fs.writeFile('files/sample-file-to-write.txt', content,
        (err) => {
            if (err) {
                throw err;
            }
            console.log('File is saved!');
        });
}

module.exports = {
    writeFile
};
Enter fullscreen mode Exit fullscreen mode

Conclusion

And that's it! We are done with reading and writing files in NodeJS. Easy peasy, right?

You can find the complete code on my GitHub. If you find it useful, consider giving it a star ⭐.

Also, you can read more such handy posts on my personal blog.

Happy Learning 😊 and Namaste 🙏.

Top comments (0)