Home  >  Article  >  Web Front-end  >  Detailed explanation of how node.js determines whether a file exists and deletes it

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

小云云
小云云Original
2017-12-22 11:41:253495browse

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")

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 ? "创建成功" : "创建失败");
});

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);
  }
};

Use

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

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!

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