The file system module in Node.js provides a variety of methods to create files, update files, and write to files. The writeFileSync method is able to perform all three functions above. In this guide, we’ll explore the writeFileSync method, how to use it in a Node.js application, and why it is a useful method. We’ll see how to handle errors while using the writeFileSync method and we’ll learn how to create files from user inputs. Finally, we will also see how to update files in a Node.js application using writeFileSync method.
Node.js File System (fs)
The Node.js file system enables file input/output (I/O) operations in Node.js applications. It allows you to work with the file system on your computer.
Methods in the fs modules can be Asynchronous or Synchronous. One differentiating factor between the Asynchronous and Synchronous methods in the Node.js application is that while the latter doesn’t block the event loop as it takes a callback function, the former does, so it is mostly used for debugging purposes. The file system module in Nodejs provides a variety of methods to create files, update files, and write to files. Among these varieties of methods in the fs modules is the writeFileSync that performs the Create files, write to files and Update files synchronously.
WriteFileSync Node.js Method
The writeFileSync is one of the synchronous methods in the fs modules. It performs its operations by blocking the Node.js event loop until its operation is completed (successful or failed). This means that whenever the writeFileSync is used in a code block, every other code after it must wait for it to be executed before execution is transferred to the next code block in the stack.
const fs = require("fs"); const fileContent = "This is an example"; fs.writeFileSync("write.txt", fileContent) console.log("File was created") console.log(fs.readFileSync("write.txt", "utf8"))
In the code above, we required the fs module, created a variable, and assigned a string value to it. Then we invoked the writeFileSync function on the instance of the fs module and passed the file and its contents to it. Finally, we printed to the terminal this statement “File was created,” and we used the readFileSync to read the content of the file. All the lines of code after the fs.writeFileSync() will not run unless the writeFileSync completes execution (failed or successful). But if the “write.txt” wasn’t successfully created, Node.js would throw an error.
The writeFileSync takes three arguments:
- File name to be created.
- Data content to write the file.
- Opportunity to specify optional parameters (encoding value, mode, and flag).
- Encoding value: A string that specifies the file encoding value.
- Flag: A string that specifies the flag used when writing to the file. The default flag is “w”.
- Mode: An integer specifying the file mode.
fs.writeFileSync(file, data, option)
Since the writeFileSync performs its operation synchronously, it is mostly never used in live applications as it reduces performance and exposes the application to security risk. These are the results of blocking an event loop in a Node.js application.
Handling errors with Node.JS writeFileSync
Node.js developers mostly used the try…catch to handle errors in the Node.js application.
The code below illustrates how to handle errors that can possibly be encountered while using writeFileSync.
const fs = require("fs"); const {Buffer} = require('buffer') try { const fileData = "Catching error" const data = Buffer.from(fileData) fs.writeFileSync("write.txt", data, {flag: "ax"}) const readAFile = fs.readFileSync('write.txt', 'utf8') console.log(readAFile) } catch (error) { console.log(error) }
The code block above should throw an error with this message: Error: EEXIST: file already exists, open ‘write.txt’ … This is because the file write.txt already exists.
If you noticed, we added the flag argument to the writeFileSync function. The value “ax” creates a file if it doesn’t exist or throws an error if the file exists. Other flag types are below:
- w: Creates a file if it doesn’t exist or overwrites the content of an existing file
- wx: Creates a file if it doesn’t already exist or throws an error if the file exists.
- ax: Creates a file if it doesn’t already exist or throws an error if it already exists.
- a: Creates a file if it doesn’t exist or appends to its existing content
Create a File in a Node.js Application From User Input
So far, we’ve manually created files, but now we need to show how to create files from user input. Node.js provides us with the readline module. This module helps us receive user input.
The code snippet below illustrates how to create a file in a Node.js application from user input using the readline module and the writeFileSync method.
const fs = require("fs"); const readline = require("readline"); const {stdin: input, stdout: output} = require("process"); const {Buffer} = require("buffer"); const createReadlineInterface = readline.createInterface({input, output}) function getUserInputToCreateFile(){ createReadlineInterface.question("Please type your file name: ", (fileName) =>{ try { if(!fileName){ return getUserInputToCreateFile() } const userInput = Buffer.from("Hi sweetCode") fs.writeFileSync(`${fileName}.txt`, userInput, {flag: "ax"}) console.log(`${fileName}.txt created`) } catch (error) { if(error.code === "EEXIST"){ console.log(`${fileName}.txt already exist`) return getUserInputToCreateFile(); } } createReadlineInterface.close() }) } getUserInputToCreateFile();
The code snippet above creates a .txt file whose name is dependent on user input. “Hi sweetCode” is written to the file. The ax flag ensures that a file is not created if it already exists. If the file name entered by the user already exists, the code prompts the user to enter another file name.
We have so far illustrated how to create a file, create files from user inputs, read the content of files and also demonstrate how to handle errors with the writeFileSync method. Going further, we’ll demonstrate how to update files with the writeFileSync method in the Node.js application.
Updating Files with writeFileSync in Node.js
Remember you read somewhere above that the writeFileSync method takes three arguments: fileName, data, and an optional parameter.
fs.writeFileSync(file, data, option)
The line of code above shows the basic syntax of the writeFileSync method.
We also stated that the optional parameters include encoding values, flag, and mode.
In this section, we’ll illustrate how to use the flag option to update a file. Updating a file means the file already exists; we’ll use this flag ‘a’ to illustrate how to update a file. The flag a creates a file if it doesn’t exist or append to an existing file’s content. We’ll use the Node.js readline/promises module to accept input from the user, create a file based on it and update the file.
Check this official documentation to see how to use Node.js readline/promises api.
The code below illustrates how to update a file in Node.js using writeFileSync.
const fs = require("fs"); const readline = require("readline"); const {stdin: input, stdout: output} = require("process"); const {Buffer} = require("buffer"); const createReadlineInterface = readline.createInterface({input, output}) function getUserInputToCreateFile(){ createReadlineInterface.question("Please type your file name: ", (fileName) =>{ try { if(!fileName){ return getUserInputToCreateFile() } const userInput = Buffer.from("\nHi sweetCode\n") fs.writeFileSync(`${fileName}.txt`, userInput, {flag: "a"}) console.log(`${fileName}.txt created`) } catch (error) { if(error.code === "EEXIST"){ console.log(`${fileName}.txt already exist`) return getUserInputToCreateFile(); } } createReadlineInterface.close() }) } getUserInputToCreateFile();
It is pretty much the same code we’ve written before; the difference is that we used a different flag: a to append to our file content.
Conclusion
We’ve successfully illustrated how to use writeFileSync to create and write files in Node.js synchronously. We also demonstrated how to handle errors while using writeFileSync, and how to use flag options in creating and writing to files.