node.js 删除文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5315138/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
node.js remove file
提问by Mark
How do I delete a file with node.js?
如何使用 node.js 删除文件?
http://nodejs.org/api/fs.html#fs_fs_rename_oldpath_newpath_callback
http://nodejs.org/api/fs.html#fs_fs_rename_oldpath_newpath_callback
I don't see a remove command?
我没有看到删除命令?
回答by Nick
回答by sourcecode
You can call fs.unlink(path, callback)for Asynchronous unlink(2) or fs.unlinkSync(path)for Synchronous unlink(2).
Where pathis file-path which you want to remove.
您可以调用fs.unlink(path, callback)异步 unlink(2) 或fs.unlinkSync(path)同步 unlink(2)。您要删除的文件路径
在哪里path。
For example we want to remove discovery.docxfile from c:/bookdirectory. So my file-path is c:/book/discovery.docx. So code for removing that file will be,
例如,我们discovery.docx要从c:/book目录中删除文件。所以我的文件路径是c:/book/discovery.docx. 所以删除该文件的代码将是,
var fs = require('fs');
var filePath = 'c:/book/discovery.docx';
fs.unlinkSync(filePath);
回答by vineet
If you want to check file before delete whether it exist or not. So, use fs.stator fs.statSync(Synchronous) instead of fs.exists. Because according to the latest node.js documentation, fs.existsnow deprecated.
如果要在删除之前检查文件是否存在。因此,请使用fs.stat或fs.statSync( Synchronous) 而不是fs.exists. 因为根据最新的 node.js文档,fs.exists现在已弃用。
For example:-
例如:-
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');
});
});
回答by Searene
I don't think you have to check if file exists or not, fs.unlinkwill check it for you.
我认为您不必检查文件是否存在,fs.unlink会为您检查。
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`);
}
});
回答by Stranger
Here is a small snippet of I made for this purpose,
这是我为此目的制作的一小段,
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.'));
}
});
回答by jasperjian
As the accepted answer, use fs.unlinkto delete files.
作为公认的答案,用于fs.unlink删除文件。
But according to Node.js documentation
但根据Node.js 文档
Using
fs.stat()to check for the existence of a file before callingfs.open(),fs.readFile()orfs.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.stat()之前调用来检查文件是否存在fs.open(),fs.readFile()或fs.writeFile()不推荐。相反,用户代码应该直接打开/读取/写入文件,并在文件不可用时处理引发的错误。建议检查文件是否存在而不操作它
fs.access()。
to check files can be deleted or not, Use fs.accessinstead
检查文件是否可以删除,fs.access改为使用
fs.access('/etc/passwd', fs.constants.R_OK | fs.constants.W_OK, (err) => {
console.log(err ? 'no access!' : 'can read/write');
});
回答by Artyom Pranovich
2019 and Node 10+ is here. Below the version using sweet async/awaitway.
2019 和 Node 10+ 来了。下面的版本使用sweet async/await方式。
Now no need to wrap fs.unlinkinto Promises nor to use additional packages (like fs-extra) anymore.
现在不需要再包装fs.unlink到 Promise 中,也不需要使用额外的包(比如fs-extra)。
Just use native fs Promises API.
只需使用原生fs Promises API。
const fs = require('fs').promises;
(async () => {
try {
await fs.unlink('~/any/file');
} catch (e) {
// file doesn't exist, no permissions, etc..
// full list of possible errors is here
// http://man7.org/linux/man-pages/man2/unlink.2.html#ERRORS
console.log(e);
}
})();
Here isfsPromises.unlinkspec from Node docs.
这是fsPromises.unlinkNode 文档中的规范。
Also please note that fs.promises API marked as experimental in Node 10.x.x (but works totally fine, though), and no longer experimental since 11.14.0.
另请注意,fs.promises API 在 Node 10.xx 中被标记为实验性(但完全正常),并且自11.14.0.
回答by Thavaprakash Swaminathan
Here below my code which works fine.
下面是我的代码,它工作正常。
const fs = require('fs');
fs.unlink(__dirname+ '/test.txt', function (err) {
if (err) {
console.error(err);
}
console.log('File has been Deleted');
});
回答by amazia
you can use delmodule to remove one or more files in the current directory. what's nice about it is that protects you against deleting the current working directory and above.
您可以使用del模块删除当前目录中的一个或多个文件。它的好处是可以保护您免于删除当前工作目录及以上目录。
const del = require('del');
del(['<your pathere here>/*']).then( (paths: any) => {
console.log('Deleted files and folders:\n', paths.join('\n'));
});
回答by Oleksii Trekhleb
You may use fs.unlink(path, callback)function. Here is an example of the function wrapper with "error-back" pattern:
您可以使用fs.unlink(path, callback)函数。这是具有“错误返回”模式的函数包装器的示例:
// 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');
}
})
};

