Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

nodejs
communitycreator

What is fs.writeFile() in Node?

Ayush Trivedi

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

fs.writeFile() is an asynchronous method for writing data in files of any type.

Syntax

fs.writeFile(File_Path, Data , callback());

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.
  • Callback: A function with an error parameter.

Code

Let’s try to write to a file and print its data in the console.

Take a look at the code below. We have two files:

  1. demo.txt: an empty text file.

  2. index.js: node code to write data in the file ‘demo.txt’.

index.js
demo.txt
const fs = require('fs');
fs.writeFile('demo.txt', 'hello Ayush' ,(err)=> {
if(err){
console.log('error',err);
}
console.log('DONE');
})
fs.readFile('demo.txt' ,(err,data)=> {
if(err){
console.log('error',err);
}
console.log(data.toString());
})

Explanation

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 use fs.writeFile() to write to a file. We provide the file path and a callback function.

  • In line 4, we have an if condition. If the write operation fails it will return err and you can use err to check the cause for failure.

  • In line 5, we print the err if it fails to write to the file.

  • In line 10, we use readFile() to check if we have successfully done the write operation and print the file content in the console.

Output

Click on Run. The output is ‘hello Ayush’, which was written by the function fs.writeFile() file.

Check line 3, which indicates we have successfully completed the task to write a file in node.

You can change the string ‘hello Ayush’ in the function fs.writeFile() file and see the output after executing the code.

RELATED TAGS

nodejs
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring