![]() |
VOOZH | about |
fs.writeFileSync() is a method in Node.js used to write data to a file synchronously. It blocks the execution of further code until the file writing operation is completed.
Node.js File System (fs) Module is a built-in module that allows developers to work with the file system on their computer. It provides methods to create, read, update, delete, and manage files and directories.
fs.writeFileSync() is a method in the Node.js File System module used to write data to a file synchronously. It ensures that the file writing process is completed before moving to the next line of code.
fs.writeFileSync( file, data, options )Parameters: This method accepts three parameters as mentioned above and described below:
1. 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.
2. data: It is a string, Buffer, TypedArray, or DataView that will be written to the file.
3. 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:
Here, we implement the fs.writeFileSync() method in Node.js.
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. PythonExample 2: This appends the names of five movies to a file named "movies.txt" five times and then reads and displays the file's contents.
Output:
File written successfully 5 times
The written file has the following contents:
Movie 0
Movie 1
Movie 2
Movie 3
Movie 4Example 3: Taking runtime input from users for file name and file data using readline module
Output
Example 4: Taking runtime input from users for file data using readline module using buffer.
Output