node.js删除文件

node.js remove file

如何使用node.js删除文件?

http://nodejs.org/api/fs.html#fs_fs_rename_oldpath_newpath_callback

我没有看到删除命令?


我认为您想使用fs.unlink

有关fs的更多信息,请参见此处。


您可以为异步unlink(2)调用fs.unlink(path, callback)或为同步unlink(2)调用fs.unlinkSync(path)
其中path是要删除的文件路径。

例如,我们要从c:/book目录中删除discovery.docx文件。所以我的文件路径是c:/book/discovery.docx。因此,用于删除该文件的代码将是

1
2
3
var fs = require('fs');
var filePath = 'c:/book/discovery.docx';
fs.unlinkSync(filePath);


如果要在删除前检查文件是否存在。因此,请使用fs.stat或fs.statSync(同步)代替fs.exists。因为根据最新的node.js文档,fs.exists现在已弃用。

例如:-

1
2
3
4
5
6
7
8
9
10
11
12
 fs.stat('./server/upload/my.csv', function (err, stats) {
   console.log(stats);//here we got all information of file in stats variable

   if (err) {
       return console.error(err);
   }

   fs.unlink('./server/upload/my.csv',function(err){
        if(err) return console.log(err);
        console.log('file deleted successfully');
   });  
});


我认为您不必检查文件是否存在,fs.unlink将为您检查它。

1
2
3
4
5
6
7
8
9
10
11
fs.unlink('fileToBeRemoved', function(err) {
    if(err && err.code == 'ENOENT') {
        // file doens't exist
        console.info("File doesn't exist, won't remove it.");
    } else if (err) {
        // other errors, e.g. maybe we don't have enough permission
        console.error("Error occurred while trying to remove file");
    } else {
        console.info(`removed`);
    }
});


这是我为此目的制作的一小段代码,

1
2
3
4
5
6
7
8
9
10
11
12
13
var fs = require('fs');
var gutil = require('gulp-util');

fs.exists('./www/index.html', function(exists) {
  if(exists) {
    //Show in green
    console.log(gutil.colors.green('File exists. Deleting now ...'));
    fs.unlink('./www/index.html');
  } else {
    //Show in red
    console.log(gutil.colors.red('File not found, so not deleting.'));
  }
});


作为接受的答案,使用fs.unlink删除文件。

但是根据Node.js文档

Using fs.stat() to check for the existence of a file before calling fs.open(), fs.readFile() or fs.writeFile() is not recommended. Instead, user code should open/read/write the file directly and handle the error raised if the file is not available.

To check if a file exists without manipulating it afterwards, fs.access() is recommended.

检查文件是否可以删除,请使用fs.access

1
2
3
fs.access('/etc/passwd', fs.constants.R_OK | fs.constants.W_OK, (err) => {
  console.log(err ? 'no access!' : 'can read/write');
});


在我的代码下面,这很好用。

1
2
3
4
5
6
7
         const fs = require('fs');
         fs.unlink(__dirname+ '/test.txt', function (err) {            
              if (err) {                                                
                  console.error(err);                                    
              }                                                          
             console.log('File has been Deleted');                          
          });


从目录中删除与regexp匹配的文件名文件。仅使用fs.unlink-删除文件,fs.readdir-从目录中获取所有文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
var fs = require('fs');
const path = '/path_to_files/filename.anyextension';

const removeFile = (fileName) => {
    fs.unlink(`${path}${fileName}`, function(error) {
        if (error) {
            throw error;
        }
        console.log('Deleted filename', fileName);
    })
}

const reg = /^[a-zA-Z]+_[0-9]+(\s[2-4])+\./

fs.readdir(path, function(err, items) {
    for (var i=0; i<items.length; i++) {
        console.log(items[i], ' ', reg.test(items[i]))
        if (reg.test(items[i])) {
           console.log(items[i])
           removeFile(items[i])
        }
    }
});

您可以使用fs.unlink(path,callback)函数。这是带有"错误返回"模式的函数包装器的示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// Dependencies.
const fs = require('fs');

// Delete a file.
const deleteFile = (filePath, callback) => {
  // Unlink the file.
  fs.unlink(filePath, (error) => {
    if (!error) {
      callback(false);
    } else {
      callback('Error deleting the file');
    }
  })
};


您可以使用del模块删除当前目录中的一个或多个文件。这样做的好处是可以防止您删除当前的工作目录及更高版本。

1
2
3
4
5
6
const del = require('del');
del(['<your pathere here>/*']).then( (paths: any) => {
   console.log('Deleted files and folders:
', paths.join('
'));
});

fs-extra提供了一种删除方法:

1
2
3
4
5
6
7
8
9
const fs = require('fs-extra')

fs.remove('/tmp/myfile')
.then(() => {
  console.log('success!')
})
.catch(err => {
  console.error(err)
})

https://github.com/jprichardson/node-fs-extra/blob/master/docs/remove.md


使用NPM模块fs-extra,该模块可以为您提供fs中的所有内容,并且所有内容都已承诺。另外,还有一个fs.remove()方法可用。


这里是您可以从文件夹中删除文件/图像的代码。

1
2
3
4
5
var fs = require('fs');
Gallery.findById({ _id: req.params.id},function(err,data){
    if (err) throw err;
    fs.unlink('public/gallery/'+data.image_name);
 });