write file to nodejs

How to Write to File in NodeJS

NodeJS is a popular JS framework that allows you to easily develop web applications and websites using JavaScript alone. While using NodeJS, you may also need to write data to files. For example, you may need to keep log of requests served by your NodeJS application. In this article, we will learn how to write to file in NodeJS.

How to Write to File in NodeJS

We will use File System API to write to files. It is one of the most common ways to write to files using NodeJS.

First, we import it to our code.

fs = require('fs');

Next, you can directly write to the file with the following commands. We will be writing to file /home/ubuntu/data.txt

fs.writeFile("/home/ubuntu/data.txt", "Hello world", function(err) {
    if(err) {
        return console.log(err);
    console.log("The file was saved!");

// Or
fs.writeFileSync('/home/ubuntu/data.txt', 'Hello world');

We have described two ways to write to files in NodeJS. The first method uses writeFile() function with a callback function. This callback function checks for errors before writing to file, and also displays a confirmation message.

The second method directly writes to file with writeFileSync() function, without any callback or error checking.

writeFile() is an asynchronous method while writeFileSync() is a synchronous method.

You can use either method depending on your requirement.

In both cases, the system user used by NodeJS process must have write access to the file. Otherwise, you will get an error.

You can check the username of NodeJS process using the following command.

$ ps aux| grep node

You can also check the permission of your target file using ls command.

$ ls -all /path/to/file

In this article, we have learnt how to write to file in NodeJS.

Also read:

How to Export JS Array to CSV File
How to Convert Unix Timestamp to Datetime Python
How to Smooth Scroll on Clicking Links
How to Import SQL File in MySQL Using Command Line
How to Change Date Format in jQuery UI Date Picker

Leave a Reply

Your email address will not be published. Required fields are marked *