javascript - fs.readFileSync 有时仅在特定情况下返回有效字符串

标签 javascript node.js visual-studio-code fs

在我的 Node 应用程序中,我有一个 init 函数:

function init() {
    if (!fs.existsSync("../schedule.json"))
        fs.createReadStream('../template.json').pipe(fs.createWriteStream('../schedule.json'));

    var content = fs.readFileSync("../schedule.json", "utf8");

    return JSON.parse(content);
}

每当我尝试从 cmd 或 git bash 运行它时,它都会因错误而崩溃:

SyntaxError: Unexpected end of JSON input

所以我在 vscode 中调试它,发现变量 content 只包含一个空字符串,这意味着 readFileSync 返回一个空字符串。

现在奇怪的是;如果在 cmd 或 git bash 中启动(无论是常规模式还是调试),或者在 vscode 中以 Debug模式启动,它永远不会工作,但如果我在 vscode 中重新启动调试器(不是启动和停止,而是实际点击重新启动按钮),那么我得到每隔一次从 readFileSync 返回的字符串形式的 json 文件的正确内容。

更新: 我尝试删除 Schedule.json 文件,然后单步执行代码。它表明它实际上没有进入 if(!fs.existsSync("../schedule.json")) 语句。 这几乎就像一个缓存错误。

最佳答案

pipe 导致事情异步发生 - 令人惊讶的是它曾经在 vscode 中工作,除非你正在逐步允许 pipe 时间完成其工作,或者当您使用重新启动时,它可能会看到上次运行的文件。

相反,您需要 wait for it to finish做它正在做的事情:

var writer = fs.createWriteStream('../schedule.json');
fs.createReadStream('../template.json').pipe(writer);
writer.on('finish', function() {
  //It's safe to read the file here
});

但是,这对您不起作用,因为您的函数期望完全同步工作并返回结果。如果您改用回调或 Promise(这可能需要也可能不需要大量工作,具体取决于对 init 的调用周围发生的情况),您可以使上述工作正常进行,或者您可以使用与您已经使用的类似的同步函数来代替 pipe:

function init() {
    var templ = null;
    if (!fs.existsSync("../schedule.json")) {
        templ = fs.readFileSync("../template.json", "utf8");
        fs.writeFileSync("../schedule.json", templ, "utf8");
    }

    var content = templ != null ?
                  templ :
                  fs.readFileSync("../schedule.json", "utf8");

    return JSON.parse(content);
}

关于javascript - fs.readFileSync 有时仅在特定情况下返回有效字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43801387/

相关文章:

node.js - 使用 connect-mongo 时处理数据库错误

visual-studio-code - 多个 _PublishedWebsites 文件夹

javascript - 日期负 30 天误差

javascript - jquery !$ 代码错误?或没有?

javascript - 指定内联事件处理程序是否会调用 eval()?

javascript - 在 VS Code 中,我可以验证我的 Javascript 但忽略特定的 typescript 错误吗?

git - VS代码: git fatal error: file is outside directory

javascript - 输入内部链接

javascript - 使用 Node.js 进行管道传输时如何跟踪写入进度?

node.js - 什么是 .ntvs_analysis.dat