NodeJS Writing and Updating Files

Go back to Tutorial

Use fs.writeFile() method to write data to a file. If file already exists then it overwrites the existing content otherwise it creates a new file and writes data into it.

Syntax: fs.writeFile(filename, data[, options], callback)

Parameter Description:

  • filename: Full path and name of the file as a string.
  • Data: The content to be written in a file.
  • options: The options parameter can be an object or string which can include encoding, mode and flag. The default encoding is utf8 and default flag is “r”.
  • callback: A function with two parameters err and fd. This will get called when write operation completes.

The following example creates a new file called test.txt and writes “Hello World” into it asynchronously.

Example: Creating & Writing File

var fs = require(‘fs’);

fs.writeFile(‘test.txt’, ‘Hello World!’, function (err) {

if (err)

console.log(err);

else

console.log(‘Write operation complete.’);

});

In the same way, use fs.appendFile() method to append the content to an existing file.

Example: Append File Content

var fs = require(‘fs’);

fs.appendFile(‘test.txt’, ‘Hello World!’, function (err) {

if (err)

console.log(err);

else

console.log(‘Append operation complete.’);

});

Open File

Alternatively, you can open a file for reading or writing using fs.open() method.

Syntax: fs.open(path, flags[, mode], callback)

Parameter Description:

  • path: Full path with name of the file as a string.
  • Flag: The flag to perform operation
  • Mode: The mode for read, write or readwrite. Defaults to 0666 readwrite.
  • callback: A function with two parameters err and fd. This will get called when file open operation completes.

Flags – The following table lists all the flags which can be used in read/write operation.

Flag Description
r Open file for reading. An exception occurs if the file does not exist.
r+ Open file for reading and writing. An exception occurs if the file does not exist.
rs Open file for reading in synchronous mode.
rs+ Open file for reading and writing, telling the OS to open it synchronously. See notes for ‘rs’ about using this with caution.
w Open file for writing. The file is created (if it does not exist) or truncated (if it exists).
wx Like ‘w’ but fails if path exists.
w+ Open file for reading and writing. The file is created (if it does not exist) or truncated (if it exists).
wx+ Like ‘w+’ but fails if path exists.
a Open file for appending. The file is created if it does not exist.
ax Like ‘a’ but fails if path exists.
a+ Open file for reading and appending. The file is created if it does not exist.
ax+ Like ‘a+’ but fails if path exists.

The following example opens an existing file and reads its content.

Example:File open and read

var fs = require(‘fs’);

fs.open(‘TestFile.txt’, ‘r’, function (err, fd) {

if (err) {

return console.error(err);

}

var buffr = new Buffer(1024);

fs.read(fd, buffr, 0, buffr.length, 0, function (err, bytes) {

if (err) throw err;

// Print only read bytes to avoid junk.

if (bytes > 0) {

console.log(buffr.slice(0, bytes).toString());

}

// Close the opened file.

fs.close(fd, function (err) {

if (err) throw err;

});

});

});

Renaming File

syntax – Asynchronous

fs.rename(oldPath, newPath, callback)

oldPath <String> | <Buffer>

newPath <String> | <Buffer>

callback – <Function>

syntax – Synchronous

fs.renameSync(oldPath, newPath)

oldPath <String> | <Buffer>

newPath <String> | <Buffer>

file rename example (asynchronously)

var fs = require(‘fs’);

fs.rename(‘c:\\dog.jpg’, ‘c:\\dog-rename.jpg’, function(err) {

if (err) {

console.log(‘ERROR: ‘ + err);

throw err;

}

console.log(‘File renamed!!’);

});

output

File renamed!!

file rename example (asynchronously)

var fs = require(‘fs’);

fs.renameSync(‘c:\\dog.jpg’, ‘c:\\dog-rename.jpg’);

Delete File

Use fs.unlink() method to delete an existing file.

Syntax: fs.unlink(path, callback);

The following example deletes an existing file.

Example:File Open and Read

var fs = require(‘fs’);

fs.unlink(‘test.txt’, function () {

console.log(‘write operation complete.’);

});

Important method of fs module

Method Description
fs.readFile(fileName [,options], callback) Reads existing file.
fs.writeFile(filename, data[, options], callback) Writes to the file. If file exists then overwrite the content otherwise creates new file.
fs.open(path, flags[, mode], callback) Opens file for reading or writing.
fs.rename(oldPath, newPath, callback) Renames an existing file.
fs.chown(path, uid, gid, callback) Asynchronous chown.
fs.stat(path, callback) Returns fs.stat object which includes important file statistics.
fs.link(srcpath, dstpath, callback) Links file asynchronously.
fs.symlink(destination, path[, type], callback) Symlink asynchronously.
fs.rmdir(path, callback) Renames an existing directory.
fs.mkdir(path[, mode], callback) Creates a new directory.
fs.readdir(path, callback) Reads the content of the specified directory.
fs.utimes(path, atime, mtime, callback) Changes the timestamp of the file.
fs.exists(path, callback) Determines whether the specified file exists or not.
fs.access(path[, mode], callback) Tests a user’s permissions for the specified file.
fs.appendFile(file, data[, options], callback) Appends new content to the existing file.

Go back to Tutorial

Get industry recognized certification – Contact us

Menu