gpt4 book ai didi

javascript - Node js/js : Text not appended in file in sequence

转载 作者:行者123 更新时间:2023-12-03 04:17:53 25 4
gpt4 key购买 nike

我正在尝试在使用 expressunirestasync 模块的代码块中写入状态信息日志,如下所示。

const fsTest = require("fs");

app.post(someURL, function (req, res) {
fsTest.appendFile("c:/fs.txt","\r\nInOf")
async.series({
one: function (callback) {
fsTest.appendFile("c:/fs.txt","\r\nInOf2")
someOperation();
fsTest.appendFile("c:/fs.txt","\r\nInOf3")
callback(false,"");
},
//form search query
two: function (callback) {
fsTest.appendFile("c:/fs.txt","\r\nInOf4")
anotherOperation();
urClient.post("https://" + server + url)
.header('Content-Type', 'application/json')
.send(qrySearchJSON)
.end(
function (response) {
});
}
}, function (err,oResp) {
errHandler();
});
});

但是我的日志总是出现乱序,如下所示:

InOf2
InOf4
InOf3
InOf

InOf
InOf2
InOf3
InOf4

InOf
InOf2
InOf4
InOf3

InOf2
InOf
InOf4
InOf3

InOf
InOf2
InOf3
InOf4

可能是什么原因以及我应该采取什么方法来解决它。

最佳答案

这是因为 fs.appendFile() 是异步的。另一方面,您可以像同步一样运行它。

最简单(不是最好)的解决方案是使用 fs.appendFileSync() - 它会按照您的预期运行。

如果您处理 appendFile 的异步特性,那就更好了。像这样的事情:

const fsTest = require("fs");

app.post(someURL, function (req, res) {
fsTest.appendFile("c:/fs.txt","\r\nInOf")
async.series({
one: function (callback) {
appendFile("c:/fs.txt","\r\nInOf2").then(function(){
someOperation();
return appendFile("c:/fs.txt","\r\nInOf3");
}).then(function(){
callback(false,"");
}).catch(function(err){})
},
//form search query
two: function (callback) {
appendFile("c:/fs.txt","\r\nInOf4").then(function(){
anotherOperation();
urClient.post("https://" + server + url)
.header('Content-Type', 'application/json')
.send(qrySearchJSON)
.end(
function (response) {
});
}).catch(function(err){});
}
}, function (err,oResp) {
errHandler();
});
});

function appendFile(file, content) {
var promise = new Promise(function(resolve, reject) {
fsTest.appendFile(file, content, function(err) {
if (err) {
reject(err);
} else {
resolve();
}
});
});

return promise
}

您可以改用 async/await 或生成器。
看看co npm 模块 - 它做了一些奇特的事情。

关于javascript - Node js/js : Text not appended in file in sequence,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44067822/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com