How to write file in nodejs

 Posted On  | Yashwant Chavan 

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.

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!!!


© technicalkeeda.com 2017

 |  Find us on Google+ |  Rss Feed

Loaded in 0.0282 seconds.