How to append to a file in Nodejs?

 Posted On  | Yashwant Chavan 

In this tutorial, You will learn how to append data to a file using nodejs. You can append content to file in synchronously and asynchronously manner.

syntax

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

Asynchronously append data to a file, creating the file if it does not yet exist. data can be a string or a buffer.

file <String> | <Buffer> | <Number> filename or file descriptor.

data <String> | <Buffer>

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

callback - <Function>

syntax

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

file <String> | <Buffer> | <Number> filename or file descriptor.

data <String> | <Buffer>

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

The synchronous version of fs.appendFile(). Returns undefined.

hello.txt

Existing file content

Hello!!!

Append data to file (asynchronously)

var fs = require('fs');

fs.appendFile('c:\\hello.txt', 'Append data!!!', function(error) {
    if (error) {
        console.log('Error:- ' + error);
        throw error;
    }
    console.log("data appended!!");
});

output

Check "hello.txt" file content.

Hello!!!Append data!!!

Append data to file (synchronously)

var fs = require('fs');
fs.appendFileSync('c:\\hello.txt', 'Append data!!!');

output

Check "hello.txt" file content again.

Hello!!!Append data!!!Append data!!!


© technicalkeeda.com 2017

 |  Find us on Google+ |  Rss Feed

Loaded in 0.0338 seconds.