NodeJS fs.appendFile 无法在 mocha 的承诺范围内工作

NodeJS fs.appendFile not working within promise in mocha

我想在我的集成测试套件中保留日志。我正在测试是否每个 'item' 都被编译并记录花费了多少时间。我正在使用 node 4.3.

首先我创建日志文件:

before(function() {
    if (!fs.existsSync("./log.csv")) {
        fs.writeFile("./log.csv", "Name; Time");
    }
});

然后在每个 it 块中我会这样做:

for (const item of items) {    
    it('compiles', function() {
        return item.testCompile();
    });
}

item class有这些方法:

testCompile() {
    return this
        .buildItem()
        .then(result => {
            // whatever testing stuff
        });
}

buildItem() {
    return this
        .internalLogicForCompiling()
        .then(result => {
            // This is not appending anything 
            fs.appendFile("./log.csv", `${item.name}; ${result.compileTime}`);

            return result;
        });
}

到目前为止文件已创建但从未更新过...知道我做错了什么吗?

PS:我假设如果文件不存在,fs 应该会抛出错误,但它不会。

您的代码通常忽略了您的 fs 调用是异步的这一事实。承诺不是魔法。如果您使用异步代码但不使用 promise,那么您需要做的不仅仅是让 promise 中的代码调用完成。

处理该问题的最简单方法是使用 fs.writeFileSyncfs.appendFileSync 而不是您进行的调用。否则,您应该这样写 before

before(function(done) {
    if (!fs.existsSync("./log.csv")) {
        fs.writeFile("./log.csv", "Name; Time", done);
    }
});

我刚刚添加了 done 回调。

buildItem 可能是这样的,这样它 returns 的承诺将不会在 appendFile 完成其工作之前解决:

buildItem() {
    return this
        .internalLogicForCompiling()
        .then(result => {
            return new Promise((resolve, reject) => {
                fs.appendFile("./log.csv", `${item.name}; ${result.compileTime}`, (err) => {
                    if (err) {
                        reject(err);
                        return;
                    }
                    resolve(result);
                });
            });
        });
}