What is fs.writeFileSync() in Node?
Along with fs.writeFile, we have fs.writeFileSync() to write data in files. The latter is a synchronous method for writing data in files.
fs.writeFileSync()is a synchronous method, and synchronous code blocks the execution of program. Hence, it is preferred and good practice to use asynchronous methods in Node.js.
Syntax
fs.writeFileSync( File_Path, Data, Options )
Parameters
File_Path: A string representing the full path of the file with the name.Data: Information that has to be written in the file.Options: Optional parameters like encoding, mode, or flag.
Code
Now, we will try to write to a file and print its data in the console.
Take a look at the code below. We have two files:
-
text.txt: An empty text file. -
index.js: Node code to write data in the filetext.txt.
const fs = require('fs')const content = 'Some content!'try {fs.writeFileSync('text.txt', content)//file written successfully} catch (err) {console.error(err)}console.log(fs.readFileSync("text.txt", "utf8"));
Explanation
The code above is a simple example of how to use fs.writeFile().
-
In line 1, we import the
fsmodule and create an object of it. -
In line 3, we define a string which we will write in the file.
-
In line 5, we use
tryso that any error thrown will be handled incatch. -
In line 6, we use
fs.writeFileSync()to write to a file. We provide the parametersfile pathanddatathat has to be written in the file. -
In line 8, we use
try catch, so iffs.writeFileSync()causes an error, it will be handled in thecatchblock. -
In line 9, we print the error
errif there is any, and this can be used to find the cause of it. -
In line 12, we use
fs.readFileSync()to read the data from filetext.txtto check if we have written data or not.