Open In App

Node.js fs.writeFileSync() Method

Last Updated : 06 Jan, 2025
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

The fs.writeFileSync() method is a synchronous method. It creates a new file if the specified file does not exist. Also, the ‘readline-sync’ module is used to enable user input at runtime.

Node.js fs.writeFileSync()

The ‘fs’ module of Node.js implements the File I/O operation. The fs module methods can be synchronous as well as asynchronous. The Asynchronous function has a callback function as the last parameter which indicates the completion of the asynchronous function. Node.js developers prefer asynchronous methods over synchronous methods as asynchronous methods never block a program during its execution, whereas the latter does. 

Syntax:

fs.writeFileSync( file, data, options )

Parameters: This method accepts three parameters as mentioned above and described below:

  • file: It is a string, Buffer, URL, or file description integer that denotes the path of the file where it has to be written. Using a file descriptor will make it behave similarly to the fs.write() method.
  • data: It is a string, Buffer, TypedArray, or DataView that will be written to the file.
  • options: It is a string or object that can be used to specify optional parameters that will affect the output. It has three optional parameters:
    • encoding: It is a string that specifies the encoding of the file. The default value is ‘utf8’.
    • mode: It is an integer that specifies the file mode. The default value is 0o666.
    • flag: It is a string that specifies the flag used while writing to the file. The default value is ‘w’.

Features

  • Synchronous Operation: Ensures that the file writing operation is completed before moving on to the next line of code.
  • File Creation and Overwriting: Automatically creates the file if it doesn’t exist or overwrites the existing file.
  • Flexible Data Input: Supports writing of strings, buffers, and other data types when appropriately converted.

Example 1: Below examples illustrate the fs.writeFileSync() method in Node.js.

// Filename - index.js

// Node.js program to demonstrate the 
// fs.writeFileSync() method 

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

let data = "This is a file containing a collection"
		+ " of programming languages.\n"
+ "1. C\n2. C++\n3. Python"; 

fs.writeFileSync("programming.txt", data); 
console.log("File written successfully\n"); 
console.log("The written has the following contents:"); 
console.log(fs.readFileSync("programming.txt", "utf8")); 

Output:

File written successfully

The written has the following contents:
This is a file containing a collection of programming languages.
1. C
2. C++
3. Python

Example 2: This example appends the names of five movies to a file named “movies.txt” five times and then reads and displays the file’s contents.

// Filename - index.js

// Node.js program to demonstrate the 
// fs.writeFileSync() method 

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

// Writing to the file 5 times 
// with the append file mode 
for (let i = 0; i < 5; i++) { 
fs.writeFileSync("movies.txt", 
	"Movie " + i + "\n", 
	{ 
	encoding: "utf8", 
	flag: "a+", 
	mode: 0o666 
	}); 
} 

console.log("File written successfully 5 times\n"); 
console.log("The written file has the following contents:"); 
console.log(fs.readFileSync("movies.txt", "utf8"));

Output:

File written successfully 5 times

The written file has the following contents:
Movie 0
Movie 1
Movie 2
Movie 3
Movie 4

Example 3: Taking runtime input from users for file name and file data using readline module 

// Filename - index.js

let readline = require('readline-sync');
let fs = require("fs");

let path = readline.question("Enter file name/path: ");

console.log("Entered path : " + path);

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

//synchronous functions may throw errors 
//which can be handled using try-catch block
try {
    fs.writeFileSync(path, data, { flag: 'a+' }); //'a+' is append mode
    console.log("File written successfully");
} catch (err) {
    console.error(err);
}
console.log("-----------------------------------------------");
try {
    const data = fs.readFileSync(path, { encoding: "utf8" });
    console.log("File content is as follows:");
    // Display the file data 
    console.log(data);
} catch (err) {
    console.log(err);
}

Output 

Example 4: Taking runtime input from users for file data using readline module using buffer.

// Filename - index.js

let fs = require("fs");
let readline = require('readline-sync');
let path = readline.question("Enter file name/path: ");

console.log("Entered path : " + path);

// 1024 specifies the buffer size. We can limit 
// the data size by this approach
let buf = new Buffer.alloc(1024);
buf = readline.question("Enter data:");


try {
    fs.writeFileSync(path, 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 content is as follows:");
    // Display the file data 
    console.log(data);
} catch (err) {
    console.log(err);
}

Output 

Summary

The fs.writeFileSync() method is a powerful and straightforward tool for writing data to files in Node.js. It provides a simple, synchronous approach to file writing, ensuring that your operations are completed in a specific order. While it’s not suitable for non-blocking or high-performance applications, it is an excellent choice for scripts, configuration writing, or any situation where synchronous file operations are appropriate.

Reference: https://nodejs.org/api/fs.html#fs_fs_writefilesync_file_data_options 



Next Article

Similar Reads

three90RightbarBannerImg