此函数应该创建一个文件,我的脚本按顺序包含了其中的20个
const fs = require('fs');
createFile( file.name + files.create_meta, blueprint.create_meta, data )
此功能创建内容
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);
})
}
有时可以正常工作,但是我经常收到以下错误消息:
[Error: ENOENT: no such file or directory, open ]
如果出现此消息,则说明文件没有创建,因为文件开头不存在,并且错误表明函数无法在此路径中找到文件。
如何保证我的函数可以创建文件?
答案 0 :(得分:0)
您可以像这样更新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);
}