ENOENT:没有这样的文件或目录使用fs写入文件

Lio*_*cer 1 javascript node.js express ecmascript-6

我不确定我在哪里弄错了这个错误:

{ Error: ENOENT: no such file or directory, open '../dist/index.html'
    at Error (native)
  errno: -2,
  code: 'ENOENT',
  syscall: 'open',
  path: '../dist/index.html' }
Run Code Online (Sandbox Code Playgroud)

console.log("Build HTML error")在代码中放入,以查看错误是否触发并且确实触发了。我还曾经console.log($.html());看过是否生成了正确的HTML。

我的代码:

fs.readFile(__dirname + '/../app/index.html', 'utf8', (err, markup) => {
    if (err) {
        console.log("grab HTML error");
        return console.log(err);
    }

    const $ = cheerio.load(markup);

    console.log($.html());
    $('head').prepend('<link rel="stylesheet" href="styles.css">');

    fs.writeFile('../dist/index.html', $.html(), 'utf8', err => {
       if (err) {
           console.log("Build HTML error");
           return console.log(err);
       }
       console.log('index.html written to /dist'.green);
    });
});
Run Code Online (Sandbox Code Playgroud)

如您所见,我将dist目录放置在正确的位置,并且webpack生成并生成了其他生成的文件

项目结构:

在此处输入图片说明

Dav*_*yon 7

我相当确定这与您的相对路径有关。您应该使用与以前相同的路径策略readFile

fs.writeFile(__dirname + '/../dist/index.html', $.html(), 'utf8', err => {
Run Code Online (Sandbox Code Playgroud)