Contents

Working with the File System

The Node.js fs (File System) module provides an API for interacting with the file system in a manner closely modeled around standard POSIX functions. You can perform operations like reading, writing, creating, and deleting files and directories using this module. This section covers the essential file system operations you’ll often need.

Reading Files Asynchronously and Synchronously

Node.js allows you to read files either asynchronously (non-blocking) or synchronously (blocking).

Reading Files Asynchronously with fs.readFile

The asynchronous method fs.readFile reads the entire contents of a file. It is non-blocking, meaning other operations can continue while the file is being read.

Example:

				
					const fs = require('fs');

fs.readFile('example.txt', 'utf8', (err, data) => {
  if (err) {
    console.error('Error reading the file:', err);
    return;
  }
  console.log('File contents:', data);
});


				
			
  • 'example.txt': The path to the file you want to read.
  • 'utf8': The encoding format (optional). If you omit this, the data will be returned as a buffer.
  • Callback function: Receives two arguments, err and data. If an error occurs, err contains the error object. Otherwise, data contains the file contents.
Reading Files Synchronously with fs.readFileSync

The synchronous method fs.readFileSync reads the file and blocks the execution until the operation is complete. This can be useful for situations where you need to ensure that the file has been read before proceeding.

Example:

				
					const fs = require('fs');

try {
  const data = fs.readFileSync('example.txt', 'utf8');
  console.log('File contents:', data);
} catch (err) {
  console.error('Error reading the file:', err);
}


				
			
  • fs.readFileSync works similarly to fs.readFile, but it returns the file contents directly and uses a try-catch block to handle errors.

Writing to Files

Node.js allows you to write to files either by overwriting the file or appending to it.

Writing to a File with fs.writeFile

The asynchronous method fs.writeFile writes data to a file, replacing the file if it already exists.

Example:

				
					const fs = require('fs');

fs.writeFile('example.txt', 'Hello, World!', (err) => {
  if (err) {
    console.error('Error writing to the file:', err);
    return;
  }
  console.log('File has been written!');
});


				
			
    • 'example.txt': The file to write to (it will be created if it doesn’t exist).
    • 'Hello, World!': The data to write to the file.
    • Callback function: Called after the write operation is complete, handling any errors that may occur.
    Appending to a File with fs.appendFile

    The fs.appendFile method adds data to the end of the file. If the file doesn’t exist, it creates a new one.

    Example:

				
					const fs = require('fs');

fs.appendFile('example.txt', ' This is appended text.', (err) => {
  if (err) {
    console.error('Error appending to the file:', err);
    return;
  }
  console.log('Data has been appended!');
});



				
			
  • 'example.txt': The file to append to.
  • ' This is appended text.': The data to append.

Creating and Deleting Files and Directories

Node.js provides several methods for creating and deleting files and directories.

Creating a Directory with fs.mkdir

The fs.mkdir method creates a new directory.

Example:

				
					const fs = require('fs');

fs.mkdir('new_directory', (err) => {
  if (err) {
    console.error('Error creating the directory:', err);
    return;
  }
  console.log('Directory created!');
});



				
			
  • 'new_directory': The name of the directory to create.
Deleting a Directory with fs.rmdir

The fs.rmdir method removes a directory. The directory must be empty for this operation to succeed.

Example:

				
					const fs = require('fs');

fs.rmdir('new_directory', (err) => {
  if (err) {
    console.error('Error removing the directory:', err);
    return;
  }
  console.log('Directory removed!');
});



				
			
    • 'new_directory': The name of the directory to delete.
    Creating a File with fs.open

    The fs.open method creates a new file. It can be used to create an empty file.

    Example:

				
					const fs = require('fs');

fs.open('newfile.txt', 'w', (err, file) => {
  if (err) {
    console.error('Error creating the file:', err);
    return;
  }
  console.log('File created:', file);
});



				
			
  • 'newfile.txt': The file to create.
  • 'w': The flag indicating the file is opened for writing. If the file doesn’t exist, it is created.
Deleting a File with fs.unlink

The fs.unlink method deletes a file.

Example:

				
					const fs = require('fs');

fs.unlink('example.txt', (err) => {
  if (err) {
    console.error('Error deleting the file:', err);
    return;
  }
  console.log('File deleted!');
});


				
			
  • 'example.txt': The file to delete.

Conclusion

Working with the file system in Node.js is straightforward and powerful. The fs module allows you to perform a variety of operations, including reading and writing files both synchronously and asynchronously, and managing the file system by creating and deleting files and directories. Understanding these operations is crucial for developing Node.js applications that interact with the file system, such as web servers, CLI tools, and file management systems.