JavaScript

How to Write Files Synchronously Using fs.writeFileSync() in Node.js?

Node.js “fs(File System)” module performs I/O operations on the file system with the help of its synchronous and asynchronous methods. These methods include “writeFile()”, “writeFileSync()” “readFile()”, “readFileSync()” and much more. For instance, the “fs.writeFileSync()” method is utilized to write a file synchronously.

The “fs.writeFileSync()” is a synchronous method that writes data into a file if it is not present in the system. Its synchronous nature stops the execution of all other operations until its specified task i.e. writing a file is not completed. It is mostly used in situations when the user wants to execute the code line by line in a sequential manner.

This post will demonstrate how to write files synchronously using “fs.writeFileSync()” in Node.js.

How to Write Files Synchronously using “fs.writeFileSync()” in Node.js?

To write a file synchronously, apply the “fs.writeFileSync()” method with the help of its generalized syntax that is written below:

fs.writeFileSync( file, data, options )

According to the above syntax the “fs.writeFileSync()” supports the following three parameters:

  • file: It specifies the exact path of the sample file or its name that needs to be used to write some data. It should be specified in double/single quotes.
  • data: It specifies the content that will be written in the created file.
  • options: It denotes the optional parameters that are listed below:
  • encoding: It holds the encoding type i.e. “utf-8” string format. The default value of this option is “null”.
  • mode: It refers to an integer that represents the file mode(permissions). Its default value is “0o666”
  • flag: It indicates the operation performed on the specified file such as read, and write. Its default value is “w”.

Now use the above-defined syntax practically.

Prerequisites

Before moving on to the practical implementation, look at the folder structure of the Node.js Project:

In the above folder structure, the “app.js” is an empty file that is created to write all the JavaScript code to perform the defined task.

Example 1: Write Files Synchronously Using “Default” Values of “fs.writeFileSync()” Method

This example applies the “fs.writeFileSync()” method to write a file synchronously using its default values:

const fs = require('fs')

const content = 'Welcome to Linuxhint!'

try {

  fs.writeFileSync('myFile.txt', content)

} catch (err) {

  console.error(err)

}

console.log(fs.readFileSync("myFile.txt", "utf8"));

In the above code lines:

  • First, the “fs” variable imports the File System module(fs) with the help of the “require()” method.
  • Next, the “content” variable specifies the file data that the user wants to write in the file.
  • After that, the “try” statement defines a code block that applies the “writeFileSync()” method to write the “myFile.txt” with the specified “content”.
  • If an error occurs during the creation of a file, then the “catch” statement will execute that applies the “console.error()” method to display an error message.
  • Lastly, the “fs.readFileSync()” method is utilized to read the written file content in the “utf8” string format.

Output

Execute the following command to initiate the “app.js” file:

node app.js

It can be seen that the terminal shows the specified file(myFile.txt) content that is written successfully in the current Node.js project:

Example 2: Write Files Using Different“Options” of “fs.writeFileSync()” Method

This example utilizes the multiple options of the “fs.writeFileSync()” method to append the data of the written file:

const fs = require('fs');

let file_data = "Welcome to Linuxhint!";

fs.writeFile("myFile.txt", file_data,

{

  encoding: "utf8",

  flag: "w",

  mode: 0o666

},

(err) => {

if (err)

  console.log(err);

else {

  console.log("File written successfully\n");

  console.log("File content is as follows:");

  console.log(fs.readFileSync("myFile.txt", "utf8"));

}

});

The above code snippet:

  • Define a “for” loop having an initializer, condition, and increment statement.
  • Inside the “for” loop the “fs.writeFileSync()” method is applied that writes a file named “myFile.txt” whose content is appended using the “a+” flag.
  • After that, the “utf8” format returns the specified file content into string format and the “0o666” file mode specifies its permissions i.e. readable and writable.
  • In case of any error, the “if-else” statement will be executed.

Output

Run the below-stated command to see the output:

node app.js

Here, the output successfully contains the appended content of the written file:

Example 3: Write Files Synchronously By Taking User Input With “fs.writeFileSync()” Method

This example uses the “fs.writeFileSync()” method with the “readline-sync” module to take the user input at runtime and store it into a “buffer”.

For this purpose, first, install the “readline-sync” module into the current Node.js project with the help of the following command:

npm install --save readline-sync

The specified “readline-sync” module is successfully added to the Node.js project.

Now, follow the given code lines:

var fs = require("fs");

var readline = require('readline-sync');

var file = readline.question("Enter file name: ");

var buf = Buffer.alloc(1024);

buf = readline.question("Enter file data:");

try {

fs.writeFileSync(file, buf,{flag:'a+'});

console.log("File written successfully");

} catch(err) {

console.error(err);

}

console.log("---------------------");

try{

const data = fs.readFileSync(path,{encoding: "utf8"});

console.log("File Data is:");

console.log(data);

}catch(err){

console.log(err);

}

The above code block:

  • Firstly, import the “readline-sync” module by using the “require()” method similar to the “fs” module.
  • Next, use the “readline” module and the linked “question()” method that first takes the user input and then displays its replay as output.
  • After that, create a “Buffer” by allocating the size of “1024” bytes.
  • Once it is done, then apply the “readline.question()” method for asking the file data from the user and displaying it as an output.
  • Next, define the “try” statement that uses the “fs.writeFileSync()” method to write the specified file into the buffer and append it with the entered content using the “a+” flag.
  • Now, use the “console.log()” method to display the verification message.
  • If any error occurs during the whole process, then the “catch” statement will be executed.
  • Lastly, apply the “fs.readFileSync()” method to read the entire file data that is created using the “fs.writeFileSync()”.

Output

Initiate the “app.js” file using the stated command:

node app.js

From the below result, it can be observed that the specified file is written at runtime whose content is stored into the buffer:

That’s all about writing files synchronously using the “fs.writeFileSync()” method.

Conclusion

To write a file synchronously in Node.js, use the inbuilt “fs.writeFileSync()” method. The working of this method relies on its generalized syntax that works on three parameters: “file”, “data” and “options”. This method creates the file in the specified location if it does not exist. This post has demonstrated all possible approaches to writing files synchronously using “fs.writeFileSync()” in Node.js.

About the author

Areej Nadeem

I am a technical author holding a Bachelor’s degree in Computer Science. I am passionate about writing and learning new technologies and sharing my knowledge with the rest of the world.