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.
fs.writeFileSync( File_Path, Data, Options )
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.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 file text.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"));
The code above is a simple example of how to use fs.writeFile()
.
In line 1, we import the fs
module 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 try
so that any error thrown will be handled in catch
.
In line 6, we use fs.writeFileSync()
to write to a file. We provide the parameters file path
and data
that has to be written in the file.
In line 8, we use try catch
, so if fs.writeFileSync()
causes an error, it will be handled in the catch
block.
In line 9, we print the error err
if 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 file text.txt
to check if we have written data or not.