Home  >  Article  >  Web Front-end  >  How to delete all files in nodejs

How to delete all files in nodejs

PHPz
PHPzOriginal
2023-04-05 09:10:39975browse

Node.js is a JavaScript runtime environment based on the Chrome V8 engine that uses an event-driven, non-blocking I/O model, making it ideal for building high-performance, scalable web applications. In Node.js, sometimes you need to delete all files in a certain directory. Let’s introduce the method of deleting all files in Node.js.

In Node.js, deleting all files in the directory can be completed through the following steps:

1. Introduce the fs module

Node.js provides the fs module, this The module provides an API for file reading and writing operations. We can use it to handle file-related operations. First, we need to introduce the fs module. The code is as follows:

const fs = require('fs');

2. Define the delete file function

Define a recursive function to delete all files under the specified path. The specific implementation is as follows:

function deleteAllFiles(path) {
  let files = [];
  if( fs.existsSync(path) ) {
    files = fs.readdirSync(path);
    files.forEach(function(file,index){
      let curPath = path + "/" + file;
      if(fs.statSync(curPath).isDirectory()) { // recurse
        deleteAllFiles(curPath);
      } else { // delete file
        fs.unlinkSync(curPath);
      }
    });
    fs.rmdirSync(path);
  }
}

3. Call the delete file function

Call the function just defined and pass in the directory path. Start deleting all files, the code is as follows:

deleteAllFiles('path/to/dir');

The complete code is as follows:

const fs = require('fs');

function deleteAllFiles(path) {
  let files = [];
  if( fs.existsSync(path) ) {
    files = fs.readdirSync(path);
    files.forEach(function(file,index){
      let curPath = path + "/" + file;
      if(fs.statSync(curPath).isDirectory()) { // recurse
        deleteAllFiles(curPath);
      } else { // delete file
        fs.unlinkSync(curPath);
      }
    });
    fs.rmdirSync(path);
  }
}

deleteAllFiles('path/to/dir');

As you can see, it is not complicated to use Node.js to delete all files in the specified directory. You only need to introduce the fs module , define a recursive function and then call it.

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

Statement:
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