The Wayback Machine - https://web.archive.org/web/20240628141803/https://www.geeksforgeeks.org/node-js-fs-writefilesync-method/
Open In App

Node.js fs.writeFileSync() Method

Last Updated : 28 May, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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.

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. 

Blocking the main thread is malpractice in Node.js, thus synchronous functions should only be used for debugging or when no other options are available.  

 

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’.

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

Example 1:

javascript




// 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: 

javascript




// 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 

javascript




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.

javascript




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 

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



Previous Article
Next Article

Similar Reads

Node.js Automatic restart Node.js server with nodemon
We generally type following command for starting NodeJs server: node server.js In this case, if we make any changes to the project then we will have to restart the server by killing it using CTRL+C and then typing the same command again. node server.js It is a very hectic task for the development process. Nodemon is a package for handling this rest
1 min read
Top 3 Best Packages Of Node.js that you should try being a Node.js Developer
Node.js is an open-source and server-side platform built on Google Chrome's JavaScript Engine (V8 Engine). Node.js has its own package manager called NPM( Node Package Manager) which has very useful and incredible libraries and frameworks that makes our life easier as a developer to work with Node.js. The 3 Best Packages of Node.js that you should
4 min read
Javascript Program For Inserting A Node After The N-th Node From The End
Insert a node x after the nth node from the end in the given singly linked list. It is guaranteed that the list contains the nth node from the end. Also 1 &lt;= n. Examples: Input : list: 1-&gt;3-&gt;4-&gt;5 n = 4, x = 2 Output : 1-&gt;2-&gt;3-&gt;4-&gt;5 4th node from the end is 1 and insertion has been done after this node. Input : list: 10-&gt;8
5 min read
Javascript Program For Swapping Kth Node From Beginning With Kth Node From End In A Linked List
Given a singly linked list, swap kth node from beginning with kth node from end. Swapping of data is not allowed, only pointers should be changed. This requirement may be logical in many situations where the linked list data part is huge (For example student details line Name, RollNo, Address, ..etc). The pointers are always fixed (4 bytes for most
5 min read
Node.js Connect Mysql with Node app
Node.js is a powerful platform for building server-side applications, and MySQL is a widely used relational database. Connecting these two can enable developers to build robust, data-driven applications. In this article, we'll explore how to connect a Node.js application with a MySQL database, covering the necessary setup, configuration, and basic
2 min read
How to resolve 'node' is not recognized as an internal or external command error after installing Node.js ?
Encountering the error message ‘node’ is not recognized as an internal or external command after installing Node.js can be frustrating, especially when you’re eager to start working on your project. This error usually means that your system cannot find the Node.js executable because the path to it is not set correctly in your system's environment v
2 min read
Node.js Http2ServerRequest.method Method
The Http2ServerRequest.method is an inbuilt application programming interface of class Http2ServerRequest within the http2 module which is used to get the string representation of the request method. Syntax: const request.method Parameters: This method does not accept any argument as a parameter. Return Value: This method returns the string represe
3 min read
Node.js http.IncomingMessage.method Method
The http.IncomingMessage.method is an inbuilt application programming interface of class Incoming Message within the inbuilt http module which is used to get the type of request method as a string. Syntax: request.method Parameters: This method does not accept any argument as a parameter. Return Value: This method returns the request type name as a
2 min read
Node.js URLSearchParams.has() Method
In URLSearchParams interface, the has() method returns a Boolean which tells us that if the parameter with input name exists it will return true, else false. Syntax: var Bool = URLSearchParams.has(name) Returns: True - if name present, else it will return False. Parameters: name - Input the name of the parameter. Example1: let url = new URL('https:
1 min read
Node.js hmac.update() Method
The hmac.update() method is an inbuilt method of class HMAC within the crypto module which is used to update the data of hmac object. Syntax: hmac.update(data[, inputEncoding])Parameters: This method takes the following two parameters: data: It can be of string, Buffer, TypedArray, or DataView type. It is the data that is passed to this function.in
2 min read
three90RightbarBannerImg