Tuesday, June 4, 2024

Writing a File in Node.js

In the post Reading a File in Node.js we saw how to use methods of fs module to read a file. In this post we'll see how to write a file in Node.js using the methods of the fs module.

How to write to a file in Node.js

In the fs module there are two methods to write to a file.

fs.writeFile()- This functions writes the file content in a non-blocking, asynchronous manner, replacing the file if it already exists. A callback function is provided which is called when the file write operation is completed.

fs.writeFileSync()- It is the synchronous function for writing content to a file which means it blocks while the write operation is in progress. The function returns undefined.

Apart from these two methods there is also a writeFile() function in the fs.promises API which asynchronously writes to a file and returns a Promise object which is resolved with no arguments upon success. Thus, you don't need a callback function.

Using fs.writeFile()

Syntax of fs.writeFile() method is as given below.

fs.writeFile( file, data, options, callback )
The four parameters are described below-
  1. file- Path to the file where content has to be written or file descriptor (a number returned by opening the file using the open() method).
  2. data- Content to be written to the file. It can be of type string, Buffer, TypedArray, DataView.
  3. options- It specifies optional parameters that can be provided with write operation. Type can be either string or object. Optional parameters are described below-
    • encoding- A string value specifying the encoding of the file. Default is 'utf8'
    • mode- An integer value specifying the file mode. Default is 0o666 which means both read and write.
    • flag- Flag used in write operation. Default flag is 'w' which means open file for writing, file is created if it doesn't exist or truncated if it exists.
    • flush- If all data is successfully written to the file, and flush is true, fs.fsync() is used to flush the data. Default value is false.
    • signal- Allows aborting an in-progress writeFile
  4. callback- A function that is called when the file operation completes. Takes one argument err which denotes the error that can be thrown if write operation fails.

fs.writeFile () Example

const fs = require('fs');
const path = require('path');

const content = 'Hello World from NodeJS!!';

fs.writeFile(path.join(__dirname, 'Hello.txt'), content, (err)=>{
    if(err){
        console.error('Error while writing to a file', err);
        return;
    }
});

If you want to give optional parameters then you can pass them as shown below-

const fs = require('fs');
const path = require('path');

const content = 'Hello World from NodeJS!!';

fs.writeFile(path.join(__dirname, 'Hello.txt'), content,  {
    encoding: "utf8",
    flag: "w",
    mode: 0o666
  }, (err)=>{
    if(err){
        console.error('Error while writing to a file', err);
        return;
    }
    console.log('File written Successfully');
});

Using fs.writeFileSync()

Syntax of fs.writeFileSync() method is as given below

fs.writeFileSync(file, data, options)

Description of parameters is similar to fs.writeFile()

fs.writeFileSync() Example

const fs = require('fs');
const path = require('path');

const content = 'Hello World from NodeJS!!';

try {
    fs.writeFileSync(path.join(__dirname, 'Hello.txt'), content);
    console.log('File written Successfully');
} catch (err) {
    console.error(err);
}

Using fsPromises.WriteFile()

Syntax of fsPromises.writeFile() method is as given below.

fsPromises.writeFile(file, data, options)

Description of parameters is similar to fs.writeFile() method as given above.

fsPromises.WriteFile() Example

const fs = require('fs');
const fsPromises = fs.promises;
const path = require('path');

async function writeFile(filePath) {
    try {
        const content = 'Hello World from NodeJS';
        await fsPromises.writeFile(filePath, content);
    } catch (err) {
        console.log(err);
    }
}

That's all for this topic Writing a File in Node.js. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Appending a File in Node.js
  2. NodeJS Blocking Non-blocking Code
  3. Node.js REPL
  4. NodeJS NPM Package Manager
  5. Creating HTTP server in Node.js

You may also like-

  1. Difference Between HashMap And ConcurrentHashMap in Java
  2. ConcurrentSkipListMap in Java With Examples
  3. JSX in React
  4. Ternary Operator in Python
  5. Dependency Injection in Spring Framework
  6. Spring Integration With Quartz Scheduler

No comments:

Post a Comment