Node.js Fs创建文件,如果不存在

问题描述 投票:0回答:1

不确定为什么这行不通,我已经浏览过类似的线程,但是无法解决。我正在尝试检查文件(config.json)是否存在以及是否没有创建它。

代码:

try {
  if (fs.existsSync('./config.json')) {
    //config.json exists
  }
} catch(err) {
    fs.writeFile('config.json', configTemplate, function (err) {
      if (err) throw err;
      console.log('File is created successfully.');
    });
}

这会在控制台中给我以下错误,并且不会创建文件:

fs.js:114
    throw err;
    ^

Error: ENOENT: no such file or directory, open './config.json'

感谢您对此的任何输入!

javascript node.js fs
1个回答
0
投票

尝试一下,让我知道它是否有效,还要确保将其运行到的目录位于console.log(__dirname);中,并查看该目录中正在发生的事情

if(fs.existsSync('./config.json')) {
    // logic if exists
} else {
    fs.writeFile('config.json', configTemplate, (err) => {
        if (err) console.log(err);

        console.log('Successfully created')
    })
}

如果您想使用trycatch,您可以这样做:

try {
    if (fs.existsSync('./config.json')) {
        // logic if exists
    } else {
        fs.writeFile('config.json', configTemplate, (err) => {
            if (err) throw err;

            console.log('Successfully created')
        })
    }
} catch(err) {
    // handle error
    console.log(err);
}

它确实为我输出了消息

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.