Node FS Module in Node.js

Node FS is the built-in File System module in Node.js. It lets a Node.js program read, create, write, append, rename, copy, delete, and inspect files and folders on the local file system.

You do not need to install fs from npm. The module is part of Node.js itself, so every Node.js project can use it directly with require('fs') in CommonJS files or import syntax in ES modules.

Node FS

Node FS File Operations

With Node FS, you may do following actions on files :

  • Reading files
  • Creating or Overwriting files
  • Updating files
  • Deleting files
  • Renaming files

The same module also supports many other file-system tasks, such as checking whether a path exists, reading directory contents, copying files, creating folders, removing folders, and reading file metadata such as size and modified time.

Node FS taskCommon methodTypical use
Read a filefs.readFile()Load text, JSON, logs, templates, or configuration data.
Write a filefs.writeFile()Create a new file or replace the content of an existing file.
Append to a filefs.appendFile()Add new content at the end of a file, such as log entries.
Rename or move a filefs.rename()Change the file name or move it to another path on the same file system.
Delete a filefs.unlink()Remove a file from the file system.
Create a directoryfs.mkdir()Create one folder or nested folders for output files.
Read a directoryfs.readdir()List the files and folders inside a directory.

Include Node.js FS Module

To include Node.js FS module in Node.js program, use the following require() statement.

</>
Copy
var fs = require('fs');

In modern JavaScript code, you may also use const with CommonJS.

</>
Copy
const fs = require('fs');

If your project uses ES modules, import the Node.js built-in module with the node: prefix.

</>
Copy
import fs from 'node:fs';
import { readFile } from 'node:fs/promises';

Node FS Callback, Promise, and Synchronous APIs

The Node.js File System module provides three common styles of methods. The best choice depends on where the code runs and how you want to handle asynchronous work.

  • Callback methods, such as fs.readFile(path, callback), run asynchronously and call a function when the operation finishes.
  • Promise methods, such as fs.promises.readFile() or node:fs/promises, work well with async and await.
  • Synchronous methods, such as fs.readFileSync(), block execution until the operation finishes. They are simple for scripts, but should be used carefully in servers.

For web servers and APIs, prefer asynchronous Node FS methods so the application can continue handling other requests while file operations are in progress. Synchronous methods are more suitable for small command-line scripts, setup tasks, or reading configuration during application startup.

Read a File with Node FS

The following example reads a text file using the promise-based FS API. It uses utf8 encoding so the result is returned as a string instead of a buffer.

</>
Copy
import { readFile } from 'node:fs/promises';

async function readExample() {
  try {
    const data = await readFile('sample.txt', 'utf8');
    console.log(data);
  } catch (error) {
    console.error('Unable to read file:', error.message);
  }
}

readExample();

Use try...catch with promise-based FS methods. File operations can fail when the file does not exist, the path is wrong, the process lacks permission, or another program is using the file.

Write a File with Node FS

The writeFile() method creates a file if it does not exist. If the file already exists, it replaces the existing content with the new content.

</>
Copy
import { writeFile } from 'node:fs/promises';

async function writeExample() {
  try {
    await writeFile('message.txt', 'Hello from Node FS!\n', 'utf8');
    console.log('File written successfully.');
  } catch (error) {
    console.error('Unable to write file:', error.message);
  }
}

writeExample();
File written successfully.

When you want to add content without replacing the old content, use appendFile() instead of writeFile().

Check a File Path Before Using Node FS

Node FS methods work with paths. A path may be relative to the current working directory or absolute. For predictable results, especially in larger projects, build paths with the Node.js path module instead of manually joining strings.

</>
Copy
import path from 'node:path';
import { fileURLToPath } from 'node:url';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

const filePath = path.join(__dirname, 'data', 'users.json');
console.log(filePath);

This approach avoids common path mistakes when the script is started from a different folder.

Node FS Error Handling Tips

File system code should handle failures clearly. A file may be missing, a directory may not exist, permissions may be restricted, or the disk may be unavailable. Do not assume that a file operation will always succeed.

  • Use asynchronous FS methods for server-side request handling.
  • Use utf8 when reading or writing text files.
  • Use Buffer output when working with binary files such as images or PDFs.
  • Check and handle error codes such as ENOENT for missing files.
  • Avoid accepting user-provided file paths without validation.
  • Keep file paths inside expected directories to reduce path traversal risks.

Examples

Following tutorials, provide you examples on the possible file operations that could be done using Node.js File System builtin module.

Official Node.js FS References

For complete method signatures, options, and version-specific details, refer to the official Node.js documentation for the File System module. The Node.js learning guide on writing files with Node.js is also useful when you want a focused example of creating or replacing a file.

Node FS FAQ

What is the file system fs module in Node.js?

The fs module is a built-in Node.js module used to interact with the local file system. It provides methods to read, write, append, rename, delete, copy, and inspect files and directories.

Do I need to install fs in Node.js?

No. You do not need to install fs with npm. It is included with Node.js and can be loaded using require('fs'), import fs from 'node:fs', or promise-based imports from node:fs/promises.

Which Node FS method is used to write a file?

Use fs.writeFile() or fs.promises.writeFile() to write a file asynchronously. Use fs.writeFileSync() only when blocking execution is acceptable.

What is the difference between writeFile and appendFile in Node FS?

writeFile() creates a new file or replaces the full content of an existing file. appendFile() adds new content to the end of the file without removing the existing content.

Should I use synchronous FS methods in a Node.js server?

Use synchronous FS methods carefully in a server because they block the event loop while the file operation runs. For request handling, asynchronous callback or promise-based FS methods are usually the safer choice.

Node FS Tutorial QA Checklist

  • Confirm that the tutorial clearly says fs is built into Node.js and does not need npm installation.
  • Check that examples use valid Node.js FS imports for the module style being shown.
  • Verify that output-only blocks use the output class and JavaScript examples use language-javascript.
  • Make sure write examples explain that existing file content may be overwritten.
  • Confirm that error handling is shown or explained for file read and write operations.

Conclusion

In this Node.js Tutorial, we have learnt to work with files using Node.js FS Module. The module is built into Node.js and supports file operations through callback, promise-based, and synchronous APIs. For most application code, use asynchronous FS methods, handle errors clearly, and build file paths carefully.