【问题标题】:How to solve [Error: ENOENT: no such file or directory, open ] for writeFile()如何解决 [Error: ENOENT: no such file or directory, open ] for writeFile()
【发布时间】:2019-02-27 21:39:20
【问题描述】:

这个函数应该创建一个文件,我的脚本依次包含其中的 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 ] 

如果出现此消息,则文件未创建,因为文件开头不存在,错误表示函数在此路径中找不到文件。

我如何保证我的函数会创建文件?

【问题讨论】:

  • 您能否更新问题以显示您如何将其中的 20 个包含在一个序列中?

标签: javascript node.js fs writefile


【解决方案1】:

你可以像这样更新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);
}




【讨论】:

    猜你喜欢
    • 2017-08-23
    • 2020-06-15
    • 2017-02-08
    • 1970-01-01
    • 2022-12-01
    • 2018-11-06
    • 1970-01-01
    • 1970-01-01
    • 2022-08-15
    相关资源
    最近更新 更多