var content;
fs.readFile('./Index.html', function read(err, data) {
if (err) {
throw err;
}
content = data;
});
console.log(content);
日志未定义,为什么?
var content;
fs.readFile('./Index.html', function read(err, data) {
if (err) {
throw err;
}
content = data;
});
console.log(content);
日志未定义,为什么?
当前回答
下面是函数将工作异步包装或承诺然后链
const readFileAsync = async (path) => fs.readFileSync(path, 'utf8');
其他回答
var content;
fs.readFile('./Index.html', function read(err, data) {
if (err) {
throw err;
}
content = data;
});
console.log(content);
这只是因为节点是异步的,它不会等待读取函数,一旦程序启动,它将控制台的值为未定义,这实际上是真的,因为没有值分配给内容变量。 我们可以使用承诺、生成器等来处理。 我们可以这样使用承诺。
new Promise((resolve,reject)=>{
fs.readFile('./index.html','utf-8',(err, data)=>{
if (err) {
reject(err); // in the case of error, control flow goes to the catch block with the error occured.
}
else{
resolve(data); // in the case of success, control flow goes to the then block with the content of the file.
}
});
})
.then((data)=>{
console.log(data); // use your content of the file here (in this then).
})
.catch((err)=>{
throw err; // handle error here.
})
如前所述,fs。readFile是一个异步动作。这意味着当您告诉节点读取一个文件时,您需要考虑这将花费一些时间,同时,节点继续运行以下代码。在你的例子中,它是:console.log(content);。
这就像把代码的一部分发送到很远的地方(比如读取一个大文件)。
看看我写的评论:
var content;
// node, go fetch this file. when you come back, please run this "read" callback function
fs.readFile('./Index.html', function read(err, data) {
if (err) {
throw err;
}
content = data;
});
// in the meantime, please continue and run this console.log
console.log(content);
这就是为什么当您记录内容时,内容仍然是空的。Node尚未检索到文件的内容。
这可以通过在回调函数中移动console.log(content)来解决,就在content = data;之后。这样,您将在节点读取文件以及内容获得值之后看到日志。
这条线可以,
const content = fs.readFileSync('./Index.html', 'utf8');
console.log(content);
下面是函数将工作异步包装或承诺然后链
const readFileAsync = async (path) => fs.readFileSync(path, 'utf8');
var fs = require('fs');
var path = (process.cwd()+"\\text.txt");
fs.readFile(path , function(err,data)
{
if(err)
console.log(err)
else
console.log(data.toString());
});