Skip to content

The Node fs module

The fs module of Node.js provides useful functions to interact with the file system

The fs module provides a lot of very useful functionality to access and interact with the file system.

There is no need to install it. Being part of the Node core, it can be used by requiring it:

const fs = require('fs')

Once you do so, you have access to all its methods, which include:

One peculiar thing about the fs module is that all the methods are asynchronous by default, but they can also work synchronously by appending Sync.

For example:

This makes a huge difference in your application flow.

Node 10 includes experimental support for a promise based API

For example let’s examine the fs.rename() method. The asynchronous API is used with a callback:

const fs = require('fs')

fs.rename('before.json', 'after.json', (err) => {
  if (err) {
    return console.error(err)
  }

  //done
})

A synchronous API can be used like this, with a try/catch block to handle errors:

const fs = require('fs')

try {
  fs.renameSync('before.json', 'after.json')
  //done
} catch (err) {
  console.error(err)
}

The key difference here is that the execution of your script will block in the second example, until the file operation succeeded.


→ Get my Node.js Handbook

I wrote 21 books to help you become a better developer:

  • HTML Handbook
  • Next.js Pages Router Handbook
  • Alpine.js Handbook
  • HTMX Handbook
  • TypeScript Handbook
  • React Handbook
  • SQL Handbook
  • Git Cheat Sheet
  • Laravel Handbook
  • Express Handbook
  • Swift Handbook
  • Go Handbook
  • PHP Handbook
  • Python Handbook
  • Linux Commands Handbook
  • C Handbook
  • JavaScript Handbook
  • Svelte Handbook
  • CSS Handbook
  • Node.js Handbook
  • Vue Handbook
...download them all now!

Related posts that talk about node: