How To Write File In Node.js

By Yashwant Chavan, Views 7641, Last updated on 02-Mar-2019

In this tutorial, You will learn how to write file using nodejs. This example covers writing file content in asynchronous(non-blocking) and synchronous (blocking) manner.

tags nodejs

syntax - (Asynchronous Write)

fs.writeFile(file, data[, options], callback)

Asynchronously writes data to a file, replacing the file if it already exists. data can be a string or a buffer.

file <String> | <Buffer> | <Integer> filename or file descriptor

data <String> | <Buffer>

options <Object> | <String>. encoding <String> | <Null> default = utf8, mode <Integer> default = 0o666, flag <String> default = 'w'.

callback - <Function>

syntax - (Synchronous Write)

fs.writeFileSync(file, data[, options])

Synchronously writes data to a file, replacing the file if it already exists. data can be a string or a buffer.

file <String> | <Buffer> | <Integer> filename or file descriptor

data <String> | <Buffer>

options <Object> | <String>. encoding <String> | <Null> default = utf8, mode <Integer> default = 0o666, flag <String> default = 'w'.

Write file in asynchronously

var fs = require('fs');

fs.writeFile('c:\\hello.txt', 'Hello!!!', function(error) {
    if (error) {
        console.log('Error:- ' + error);
        throw error;
    }
    console.log("done!!");
});

output

Check "hello.txt" file content.

Hello!!!

Write file in synchronously

var fs = require('fs');
fs.writeFileSync('c:\\hello.txt', 'Hello again!!!');

output

Check "hello.txt" file content.

Hello again!!!
Yashwant

Yashwant

Hi there! I am founder of technicalkeeda.com and programming enthusiast. My skills includes Java,J2EE, Spring Framework, Nodejs, PHP and lot more. If you have any idea that you would want me to develop? Lets connect: yashwantchavan[at][gmail.com]