我如何删除一个文件与node.js?
http://nodejs.org/api/fs.html#fs_fs_rename_oldpath_newpath_callback
我没有看到删除命令?
我如何删除一个文件与node.js?
http://nodejs.org/api/fs.html#fs_fs_rename_oldpath_newpath_callback
我没有看到删除命令?
当前回答
从filename匹配regexp的目录中删除文件。只使用fs。Unlink -删除文件,fs。Readdir -从目录中获取所有文件
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])
}
}
});
其他回答
2019年和节点10+已经到来。下面的版本采用了甜异步/等待的方式。
现在不需要对fs进行换行。不再链接到Promises,也不再使用额外的包(比如fs-extra)。
只需使用本地fs承诺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);
}
})();
这里是fsPromises。从Node文档中断开规范链接。
另外,请注意fs。在Node 10.x中承诺API标记为实验性。X(但是工作完全正常),并且从11.14.0开始不再是实验性的。
我认为你不需要检查文件是否存在,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`);
}
});
fs.unlinkSync()如果你想同步删除文件 Fs.unlink()如果你想异步删除它。
在这里你可以找到一篇好文章。
2022的答案
不要在Nodejs中做任何同步操作
若要异步删除文件,
const { unlink } = require('fs/promises');
(async function(path) {
try {
await unlink(path);
console.log(`successfully deleted ${path}`);
} catch (error) {
console.error('there was an error:', error.message);
}
})('/tmp/hello');
裁判:https://nodejs.org/api/fs.html # promise-example
建议在使用access或stat删除前检查文件是否存在
import { access, constants } from 'fs';
const file = 'package.json';
// Check if the file exists in the current directory.
access(file, constants.F_OK, (err) => {
console.log(`${file} ${err ? 'does not exist' : 'exists'}`);
});
裁判:https://nodejs.org/api/fs.html # fsaccesspath-mode-callback
rm -rf它
require("fs").rmSync(file_or_directory_path_existing_or_not, {recursive: true, force: true});
// Added in Node.js 14.14.0.
要求(fs)。rmSync或require("fs").rm。