Writing files with Node.js
Mrityunjay-Palled
Posted on December 31, 2022
Writing data to a file is one of the most common tasks in any programming language. Now let's take a look at how we can write files in node.js
Using writeFile():
//importing file system module
const fs=require('fs')
const path='./Files/write.txt'
const data='Hello this is new data'
fs.writeFile(path,data,(err)=>{
if(err)return console.log('error occurred while writing data')
})
As we see above writeFile takes the following parameters:
path:filepath of the file to write
data:data to be written to the file
callback:If there is no error, err === null, otherwise err contains the error message.
writeFile is asynchronous in nature, means it does not effect the execution of the program.
using writeFileSync():
//importing file system module
const fs=require('fs')
const path='./Files/write.txt'
const data='Hello this is new data'
try{
fs.writeFileSync(path,data)
//file written successfully
}catch(err){
console.log('error occurred while writing data')
//error occurred
}
As we see above writeFileSync takes the following parameters:
path:filepath of the file to write
data:data to be written to the file
writeFileSync is synchronous in nature, which means the rest of the code execution will be stopped until the file writing is complete.
Using promise-based writeFile():
//importing promise-based file system module
const fs=require('fs').promises
const path='./Files/write.txt'
const data="Hello this is new data"
const fileWrite=async ()=>{
try{
await fs.writeFile(path,data)
//file written successfully
}catch(err){
console.log('error occurred while writing data')
//error occurred
}
}
fileWrite()
As we see above promise-based writeFile takes the following parameters:
path:filepath of the file to write
data:data to be written to the file
since it is promise-based we can use async-await as shown above
Posted on December 31, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.