File Handling in Nodejs

Asynchronous file handling using promises

File Handling in Nodejs

File handling

File handling involves operations such as creating, reading, writing, updating, and deleting files on our system. In Nodejs, file handling is done by using in-built File system module. It can be performed in both synchronous and asynchronous ways. The execution of further code is blocked until file handling task is completed in synchronous way. Hence, it is referred as blocking-model. Where as, asynchronous way is non-blocking in nature and rest of the code is run parallelly with file handling. So, we will use promise based asynchronous file handling in this article.

As Common JS modules are synchronous in nature, we will be using ES6 modules so, make sure to add "type" : "module" in package.json or save your program file with .mjs extension.


Importing module

To use promise based API for file handling, we use fs/promises module

import * as fs from "fs/promises"

Witting a file

To create and write contents in a file, we use writeFile method which takes file name and content as arguments .

import * as fs from "fs/promises"
try {
    await fs.writeFile("hello.txt", "Hello there, we are learning Nodejs !")
} catch (error) {
    console.log(error)
}

This method creates a new hello.txt file and writes the content. If the file exists, everything is overwritten with the new content.


Reading a file

To read contents of a file, we use readFile method which takes file name and display format as arguments .


import * as fs from "fs/promises"
try {
    // To display content in BufferStream 
    let contentInBufferStream = await fs.readFile("hello.txt")
    console.log(contentInBufferStream )
    // To display content in human readable format 
    let contentInReadableFormat = await fs.readFile("hello.txt","utf-8")
    console.log(contentInReadableFormat )
} catch (error) {
    console.log(error)
}

Appending a file

To append/add contend at the end of the file without overwriting the content, we use appendFile method. It takes file name and content as arguments.

import * as fs from "fs/promises"
try {
    await fs.appendFile("hello.txt", "a")
} catch (error) {
    console.log(error)
}

Deleting a file/folder

To delete a file or folder we use unlink or rmdir methods respectively. Both of them takes file location as an argument.

import * as fs from "fs/promises"
// To delete a file 
await fs.unlink("hello.txt")
// To delete a folder 
await fs.rmdiir("abc")