Home > Web Front-end > JS Tutorial > body text

Detailed explanation of how node.js determines whether a file exists and deletes it

小云云
Release: 2017-12-22 11:41:25
Original
3484 people have browsed it

This article mainly introduces the method of nodejs to determine the existence and deletion of files and folders. You need to use the fs module of nodejs. It analyzes the operation skills of nodejs based on the file module to determine the existence and deletion of files and folders based on the example form. Friends in need can refer to it, I hope it can help everyone.

Judge whether files and folders exist

You need to use the fs module of nodejs

Introduce

var fs= require("fs")
Copy after login

How to judge

fs.exists(path, callback)

path: The path of the determined folder and file
callback: callback function

fs.exists("dirName", function(exists) {
  console.log(exists ? "创建成功" : "创建失败");
});
Copy after login

Delete the folder and file

The fs module of node.js only provides the function of deleting the file unlink folder and the directory rmdir, so deleting them together requires us to traverse the deletion. The code is as follows

var fs = require('fs'); // 引入fs模块
function deleteall(path) {
  var files = [];
  if(fs.existsSync(path)) {
    files = fs.readdirSync(path);
    files.forEach(function(file, index) {
      var curPath = path + "/" + file;
      if(fs.statSync(curPath).isDirectory()) { // recurse
        deleteall(curPath);
      } else { // delete file
        fs.unlinkSync(curPath);
      }
    });
    fs.rmdirSync(path);
  }
};
Copy after login

Use

deleteall("./dir")//将文件夹传入即可
Copy after login

Related recommendations:

Detailed explanation of how node.js reads and writes system files and directories based on the fs module

PHP and Node.js

Solution to the asynchronous reading and writing of synchronized results in the fs module in node.js

The above is the detailed content of Detailed explanation of how node.js determines whether a file exists and deletes it. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!