gpt4 book ai didi

javascript - readFile() 内部的回调函数

转载 作者:行者123 更新时间:2023-11-28 14:33:22 28 4
gpt4 key购买 nike

我的问题是关于回调函数的工作方式。

const fs = require('fs');

let fileContents = 'initial value';
fs.readFile('file.txt', 'utf-8',function(error,res){
fileContents = res;
console.log(fileContents);
})

因此,当fs.readFile运行时,function(error,res)被调用。但是,如果我的参数为空,为什么 fileContents 会收到 txt 文件内的文本?我假设 readFile 将读取的值添加到 res 参数中。总是这样吗?

另一个问题是为什么当我删除错误时会得到null

最佳答案

读取文件看起来像这样:

 function readFile(path, cb) {
try {
// Some very complicated stuff
// All fine, call callback:
path(/*error:*/ null, /*res: */ "somedata");
} catch(error) {
path(error, /*res: */ undefined);
}
}

因此,您在回调参数中获得的内容并不取决于其名称,而是取决于其位置,因此当您这样做时:

readFile("/..", function(res) { /*...*/ });

res 将是 readFile 传回的错误,如果这是 null 则这是一件好事。

关于javascript - readFile() 内部的回调函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50682570/

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