Language: EN

como-gestionar-ficheros-nodejs

How to manage files with Node.js and the FS module

Node.js provides a module called fs (file system) that allows us to interact with the server’s file system.

This module gives us all the functions we need to perform operations such as reading, writing, modifying, and deleting files and directories.

When reading and writing files, it is important to specify the correct encoding. For example, utf8. If we are working with binary files, such as images or compressed files, we should omit the encoding to get the data unmodified.

FS module functions

Let’s look at some of the most important functions of the fs module, along with practical examples of how to use them.

Check if a file exists

The first task we often need to perform is to check for the existence of a file. For this, we use the access function, which allows us to check if a file exists and if we have permission to access it.

import { access } from 'node:fs';

access('file.txt', (err) => {
  if (err) {
    console.error('The file does not exist');
    return;
  }
  
  console.log('The file exists');
});

Copy a file

To make a copy of an existing file we use the copyFile function, which takes the name of the source file and the name of the destination file as parameters.

import { copyFile } from 'node:fs';

copyFile('source.txt', 'destination.txt', (err) => {
  if (err) throw err;
  
  console.log('File copied successfully');
});

Move a file

To rename or relocate a file, we use the rename function. This allows us to move a file from one location to another or simply change its name.

import { rename } from 'node:fs';

rename('old.txt', 'new.txt', (err) => {
  if (err) throw err;
  
  console.log('File moved successfully');
});

Delete a file

To programmatically delete a file we use the unlink function, which allows us to remove a file from the file system.

import { unlink } from 'node:fs';

unlink('file.txt', (err) => {
  if (err) throw err;
  
  console.log('File deleted successfully');
});

Read a text file

Suppose we have a file named data.txt with the following content:

This is a sample file.
It contains some lines of text.

The following code in Node.js will allow us to read this file:

import { readFile } from 'node:fs';

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

In this example, fs.readFile() takes three arguments: the name of the file (data.txt), the encoding (utf8 for text), and a callback function that is executed once the reading is complete. If the reading is successful, the content of the file is printed to the console.

Read a binary file

Suppose we have a file named data.txt but as binary, its bytes.

import { readFile } from 'node:fs';

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

Add a line to a file

To add content to an existing file, such as adding a new line, we use the appendFile function.

import { appendFile } from 'node:fs';

const newLine = 'New line to add';

appendFile('file.txt', `${newLine}\n`, (err) => {
  if (err) throw err;
  
  console.log('Line added to the file');
});

Create a new file and write to it

To create a new file and write content to it, we use the writeFile function.

import { writeFile } from 'node:fs';

const content = 'Content of the new file';

writeFile('new.txt', content, (err) => {
  if (err) throw err;
  
  console.log('New file created and content written');
});

Download the code

All the code from this entry is available for download on Github github-full