[英]How to solve [Error: ENOENT: no such file or directory, open ] for writeFile()
this function should create a file, my script include 20 of them in a sequence 这个函数应该创建一个文件,我的脚本按顺序包含了其中的20个
const fs = require('fs');
createFile( file.name + files.create_meta, blueprint.create_meta, data )
this function create the content 此功能创建内容
function createFile(filePath, blueprintPath, data) {
const blueprint = fs.readFileSync(blueprintPath, 'utf8');
const content = template(blueprint, {
email: data.email,
name: data.name,
date: data.date,
})
fs.writeFile(filePath, content, function (err) {
console.log(err);
})
}
sometime it work, but often i get an this error message: 有时它可以工作,但通常我会收到以下错误消息:
[Error: ENOENT: no such file or directory, open ]
If this message appear, the file was not created because the files not exist at the beginning and the error means that the function cannot find a file in this path. 如果出现此消息,则说明文件没有创建,因为文件开头不存在,并且该错误表明函数无法在此路径中找到文件。
how can i guarantee that my function create the files? 如何保证我的函数创建文件?
You can update createFile
function like this. 您可以像这样更新
createFile
函数。
const fs = require("fs");
function createFile(filePath, blueprintPath, data) {
if (!fs.existsSync(blueprintPath)) {
throw new Error(blueprintPath + " does not exist");
}
const blueprint = fs.readFileSync(blueprintPath, "utf8");
const content = template(blueprint, {
email: data.email,
name: data.name,
date: data.date
});
// creates an empty file if doesn't exist
fs.closeSync(fs.openSync(filePath, "w"));
fs.writeFile(filePath, content, function(err) {
console.log(err.message);
});
}
try {
// call your function in try-catch
createFile("./test.txt", "testtest", "test");
} catch (error) {
console.log(error.message);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.