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 provides us with 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 work with binary files, such as images or compressed files, we should omit the encoding to get the data without modification.

On the other hand, for large files, it is recommended to use the streams module of Node.js instead of loading all the content into memory. We will see this in the next article How to work with streams

Functions of the FS module

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

Verify if a file exists

The first task we often need to perform is to verify the existence of a file. To do 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('archivo.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('origen.txt', 'destino.txt', (err) => {
  if (err) throw err;
  
  console.log('File copied successfully');
});

Move a file

To change the name or location of 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('antiguo.txt', 'nuevo.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 delete a file from the file system.

import { unlink } from 'node:fs';

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

Reading a text file

Suppose we have a file called datos.txt with the following content:

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

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

import { readFile } from 'node:fs';

fs.readFile('datos.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 file name (datos.txt), the encoding (utf8 for text), and a callback function that runs once the reading is complete. If the reading is successful, the file content is printed to the console.

Reading a binary file

Suppose we have a file called datos.txt but as binary, its bytes.

import { readFile } from 'node:fs';

fs.readFile('datos.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('archivo.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('nuevo.txt', content, (err) => {
  if (err) throw err;
  
  console.log('New file created and content written');
});