Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Reading and Writing Files in Node.js

Tech Apr 18 9

File manipulation is a fundamental server-side feature and an essential skill for backend development.

File operations primarily involve reading and writing. Node.js provides built-in methods for these tasks, which you can invoke directly.

Creating Directories

Synchronous Method

const fileSystem = require('fs');
const targetDirectory = `${__dirname}/new_folder`;
fileSystem.mkdirSync(targetDirectory);

Node.js has a built-in file system module named fs. You must import this module before performing any file operations.

You can use the fs.mkdirSync method to create a directory synchronously. Pass the name of the directory you want to create as the argument.

__dirname refers to the absolute path of the directory where the current script resides.

Asynchronous Method

const fs = require('fs');
const dirName = `${__dirname}/new_folder`;
fs.mkdir(dirName, (creationError) => {
  if (creationError) {
    console.error('Failed to create directory:', creationError);
  }
});

The fs.mkdir method allows you to create a directory asynchronously. The first parameter is the directory name, and the second is a callback function containing an err parameter to handle potential errors.

Deleting Files

After creating directories, the natural next step would be deleting directories. However, you must empty a directory before deleting it, so we will cover deleting files first.

Deleting files can be done using both synchronous and asynchronous methods.

Synchronous: fs.unlinkSync

const fs = require('fs');
const filePath = `${__dirname}/document.txt`;
fs.unlinkSync(filePath);

By passing the file path and name to fs.unlinkSync, the specified file will be deleted.

Asynchronous: fs.unlink

const fs = require('fs');
const targetFile = `${__dirname}/document.txt`;
fs.unlink(targetFile, (deleteError) => {
  if (deleteError) {
    console.error('Error deleting file:', deleteError);
  }
});

The fs.unlink method takes two parameters: the first is the file path and name, and the second is a callback functon that handles any deletion errors.

Deleting Directories

Before deleting a directory, you must clear all files inside the target directory. You can use fs.unlinkSync or fs.unlink to remove the files first.

Synchronous

const fs = require('fs');
const folderToRemove = `${__dirname}/new_folder`;
fs.rmdirSync(folderToRemove);

Asynchronous

const fs = require('fs');
const dirPath = `${__dirname}/new_folder`;
fs.rmdir(dirPath, (removeError) => {
  if (removeError) {
    console.error('Failed to remove directory:', removeError);
  }
});

Similar to deleting files, deleting directories offers both synhcronous and asynchronous methods. The asynchronous method accepts two parameters, where the second is a callback for error handling.

Writing Data

const fs = require('fs');
const logMessage = 'Application started\n';
const writeOptions = {
  flag: 'a', // 'a' for append, 'w' for overwrite
};

fs.writeFile('output.log', logMessage, writeOptions, (writeError) => {
  if (writeError) {
    console.error('Failed to write to file:', writeError);
  }
});

The fs.writeFile method allows you to write content to a file. If the file does not exist, it will be created automatically.

fs.writeFile parameters explained:

  • First parameter: The file name.
  • Second parameter: The content to write.
  • Third parameter: The write mode (e.g., append, overwrite).
  • Fourth parameter: A callback function for error handling.

Reading Data

const fs = require('fs');
fs.readFile('output.log', (readError, fileBuffer) => {
  if (readError) {
    console.error('Unable to read file:', readError);
    return;
  }
  // fileBuffer is a Buffer (binary), convert it to a string
  console.log(fileBuffer.toString());
});

You can use the fs.readFile method to read data. The first parameter is the file name, and the second is a callback function. The err parameter handles error messages, while data contains the retrieved data.

Note that the retrieved data is returned as a Buffer (binary type). You need to use the toString() method to convert it into a readable string.

Checking if a File Exists

const fs = require('fs');
const isPresent = fs.existsSync('output.log');
console.log('File exists:', isPresent);

The fs.existsSync method checks whether a specific file exists. It returns true if the file exists, and false otherwise.

Summary

If you are using Node.js for backend development, reading and writing files is an inescapable topic. One of the most common applications for this is writing logs, such as collecting error logs.

While logs can also be stored in a database, not all computers have the same databases installed. However, if you write logs to a file, the contents can easily be opened on almost any other computer.

Related Articles

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

SBUS Signal Analysis and Communication Implementation Using STM32 with Fus Remote Controller

Overview In a recent project, I utilized the SBUS protocol with the Fus remote controller to control a vehicle's basic operations, including movement, lights, and mode switching. This article is aimed...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.