Open In App

Node.js fs.write() Method

File-writing is an important aspect of programming. Every programming language has a well-defined file module that can be used to perform file operations. JavaScript and Node.js also have file module which provides various inbuilt methods for performing read, write, rename, delete and other operations on files. The file module of Node.js is called the fs module. By default, the fs module writes files with an encoding of ‘UTF-8’.

The fs.write() method is an inbuilt application programming interface of fs module which is used to specify the position in a file to begin writing at a buffer to write, as well as which part of the buffer to write out to the file. The fs.write() method can also be used without a buffer by simply using a string variable. The examples given below demonstrate the use of buffer as well as string in the fs.write() method. It is an asynchronous method.



Syntax:

Parameters: The method accept the following parameters as mentioned above and described below:



Return Value: The callback function receives either error or the number of bytes written. If an error is received then an error message is printed else the number of bytes written is printed.

Example 1:




// Node.js program to demonstrate the     
// fs.write() method
   
// Include fs module
const fs=require("fs");
   
// File path where data is to be written
// Here, we assume that the file to be in
// the same location as the .js file
var path = 'input.txt';
   
// Declare a buffer and write the
// data in the buffer
let buffer = new Buffer.from('GeeksforGeeks: '
    + 'A computer science portal for geeks\n');
   
// The fs.open() method takes a "flag"
// as the second argument. If the file
// does not exist, an empty file is
// created. 'a' stands for append mode
// which means that if the program is
// run multiple time data will be
// appended to the output file instead
// of overwriting the existing data.
fs.open(path, 'a', function(err, fd) {
  
    // If the output file does not exists
    // an error is thrown else data in the
    // buffer is written to the output file
    if(err) {
        console.log('Cant open file');
    }else {
        fs.write(fd, buffer, 0, buffer.length, 
                null, function(err,writtenbytes) {
            if(err) {
                console.log('Cant write to file');
            }else {
                console.log(writtenbytes +
                    ' characters added to file');
            }
        })
    }
})

Output:

51 characters added to file

input.txt file data:

GeeksforGeeks: A computer science portal for geeks

Explanation:
On successful execution of the program, the data stored in the buffer is appended to the required file. In case the file does not exist beforehand, a new file is created and data is appended to it.

Example 2:




// Node.js program to demonstrate the     
// fs.write() method
   
// Include fs module
const fs=require("fs");
   
const str = "Hello world";
const filename = "input.txt";
   
fs.open(filename, "a", (err, fd)=>{
    if(err){
        console.log(err.message);
    }else{
        fs.write(fd, str, (err, bytes)=>{
            if(err){
                console.log(err.message);
            }else{
                console.log(bytes +' bytes written');
            }
        })        
    }
})

Output:

11 bytes written

input.txt file data:

Hello world

Explanation: On successful execution of the program, the string value is written(appended) to the required file.

Reference:


Article Tags :