Table of Contents
Delete files synchronously
Deleting files asynchronously
Delete empty directories
Delete non-empty directories
Summary
Home Web Front-end Front-end Q&A How to delete files in nodejs

How to delete files in nodejs

May 16, 2023 pm 09:55 PM

Node.js is a popular JavaScript back-end running environment. You can use Node.js to easily manipulate the local file system. Typically, we need to delete files frequently, and Node.js provides multiple built-in methods to simplify this process. In this article, we will discuss how to delete files using Node.js.

Node.js has a built-in File System core module, which provides many synchronous and asynchronous methods to operate the file system. Among these methods, the fs.unlink() function is used to delete files. Next we use this method to demonstrate how to delete files.

Delete files synchronously

The synchronization operation is performed sequentially, that is, it blocks the execution of the code until the operation is completed. In Node.js, we can use the fs.unlinkSync() function to delete files synchronously. The syntax of this function is as follows:

fs.unlinkSync(path)
Copy after login

where path is the path of the file to be deleted. The sample code is as follows:

const fs = require('fs');
const path = './test.txt';
  
//删除文件
try {
    fs.unlinkSync(path);
    console.log(`${path}删除成功`);
} catch (error) {
    console.log(`删除${path}失败:${error}`);
}
Copy after login

Although synchronous operation may block the application, it may be more convenient in some scenarios, such as in unit testing.

Deleting files asynchronously

The asynchronous API of Node.js will not block the execution of the application, but will notify us of the end of the operation through the callback function. In the asynchronous API, we can use the fs.unlink() function to delete files asynchronously. The syntax of this function is as follows:

fs.unlink(path, callback)
Copy after login

where, path is the path of the file to be deleted, callback is the callback function. When the file deletion operation is completed, the callback function will be called and the error message will be passed to the callback function as the first parameter. If there are no errors, the first parameter will be null or undefined. The sample code is as follows:

const fs = require('fs');
const path = './test.txt';
  
//删除文件
fs.unlink(path, (error) => {
    if(error) {
        console.log(`删除${path}失败:${error}`);
    } else {
        console.log(`${path}删除成功`);
    }
})
Copy after login

Asynchronous APIs are generally more flexible than synchronous APIs because they do not block the execution of the application. In an asynchronous operation, we can perform other operations as needed and execute the callback function after the operation is completed.

Delete empty directories

Use the fs.rmdir() function to delete empty directories. If the directory is not empty, the delete operation will fail. The syntax of this function is as follows:

fs.rmdir(path, callback)
Copy after login

Among them, path is the path of the directory to be deleted, and callback is the callback function. When the directory deletion operation is completed, the callback function will be called and the error message will be passed to the callback function as the first parameter. If there are no errors, the first parameter will be null or undefined.

Delete non-empty directories

If you want to delete non-empty directories, you can use the third-party module rimraf. rimraf provides a simple interface for deleting files and directories including non-empty directories. First, we need to install rimraf using npm:

npm install rimraf
Copy after login

Then, we can use the rimraf() function to delete non-empty directories. The syntax of this function is as follows:

const rimraf = require('rimraf');

rimraf(path, (error) => {
    if(error) {
        console.log(`删除${path}失败:${error}`);
    } else {
        console.log(`${path}删除成功`);
    }
})
Copy after login

Among them, path is the path of the directory to be deleted, and callback is the callback function. When the directory deletion operation is completed, the callback function will be called and the error message will be passed to the callback function as the first parameter. If there are no errors, the first parameter will be null or undefined.

Summary

Node.js provides multiple methods to delete files. For simple file deletion operations, we can use the fs.unlink() or fs.unlinkSync() function. The former is an asynchronous operation and the latter is a synchronous operation. If you want to delete an empty directory, you can use the fs.rmdir() function. If you want to delete a non-empty directory, you can use the rimraf() function. We should choose the appropriate method to delete files according to the specific scenario.

The above is the detailed content of How to delete files in nodejs. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

React's Role in HTML: Enhancing User Experience React's Role in HTML: Enhancing User Experience Apr 09, 2025 am 12:11 AM

React combines JSX and HTML to improve user experience. 1) JSX embeds HTML to make development more intuitive. 2) The virtual DOM mechanism optimizes performance and reduces DOM operations. 3) Component-based management UI to improve maintainability. 4) State management and event processing enhance interactivity.

What are the limitations of Vue 2's reactivity system with regard to array and object changes? What are the limitations of Vue 2's reactivity system with regard to array and object changes? Mar 25, 2025 pm 02:07 PM

Vue 2's reactivity system struggles with direct array index setting, length modification, and object property addition/deletion. Developers can use Vue's mutation methods and Vue.set() to ensure reactivity.

React Components: Creating Reusable Elements in HTML React Components: Creating Reusable Elements in HTML Apr 08, 2025 pm 05:53 PM

React components can be defined by functions or classes, encapsulating UI logic and accepting input data through props. 1) Define components: Use functions or classes to return React elements. 2) Rendering component: React calls render method or executes function component. 3) Multiplexing components: pass data through props to build a complex UI. The lifecycle approach of components allows logic to be executed at different stages, improving development efficiency and code maintainability.

React and the Frontend: Building Interactive Experiences React and the Frontend: Building Interactive Experiences Apr 11, 2025 am 12:02 AM

React is the preferred tool for building interactive front-end experiences. 1) React simplifies UI development through componentization and virtual DOM. 2) Components are divided into function components and class components. Function components are simpler and class components provide more life cycle methods. 3) The working principle of React relies on virtual DOM and reconciliation algorithm to improve performance. 4) State management uses useState or this.state, and life cycle methods such as componentDidMount are used for specific logic. 5) Basic usage includes creating components and managing state, and advanced usage involves custom hooks and performance optimization. 6) Common errors include improper status updates and performance issues, debugging skills include using ReactDevTools and Excellent

What are the benefits of using TypeScript with React? What are the benefits of using TypeScript with React? Mar 27, 2025 pm 05:43 PM

TypeScript enhances React development by providing type safety, improving code quality, and offering better IDE support, thus reducing errors and improving maintainability.

How can you use useReducer for complex state management? How can you use useReducer for complex state management? Mar 26, 2025 pm 06:29 PM

The article explains using useReducer for complex state management in React, detailing its benefits over useState and how to integrate it with useEffect for side effects.

What are functional components in Vue.js? When are they useful? What are functional components in Vue.js? When are they useful? Mar 25, 2025 pm 01:54 PM

Functional components in Vue.js are stateless, lightweight, and lack lifecycle hooks, ideal for rendering pure data and optimizing performance. They differ from stateful components by not having state or reactivity, using render functions directly, a

React and the Frontend Stack: The Tools and Technologies React and the Frontend Stack: The Tools and Technologies Apr 10, 2025 am 09:34 AM

React is a JavaScript library for building user interfaces, with its core components and state management. 1) Simplify UI development through componentization and state management. 2) The working principle includes reconciliation and rendering, and optimization can be implemented through React.memo and useMemo. 3) The basic usage is to create and render components, and the advanced usage includes using Hooks and ContextAPI. 4) Common errors such as improper status update, you can use ReactDevTools to debug. 5) Performance optimization includes using React.memo, virtualization lists and CodeSplitting, and keeping code readable and maintainable is best practice.

See all articles