Get data from fs.readFile

前端 未结 15 2525
滥情空心
滥情空心 2020-11-22 15:38
var content;
fs.readFile(\'./Index.html\', function read(err, data) {
    if (err) {
        throw err;
    }
    content = data;
});
console.log(content);
         


        
15条回答
  •  半阙折子戏
    2020-11-22 16:26

    To put it roughly, you're dealing with node.js which is asynchronous in nature.

    When we talk about async, we're talking about doing or processing info or data while dealing with something else. It is not synonymous to parallel, please be reminded.

    Your code:

    var content;
    fs.readFile('./Index.html', function read(err, data) {
        if (err) {
            throw err;
        }
        content = data;
    });
    console.log(content);
    

    With your sample, it basically does the console.log part first, thus the variable 'content' being undefined.

    If you really want the output, do something like this instead:

    var content;
    fs.readFile('./Index.html', function read(err, data) {
        if (err) {
            throw err;
        }
        content = data;
        console.log(content);
    });
    

    This is asynchronous. It will be hard to get used to but, it is what it is. Again, this is a rough but fast explanation of what async is.

提交回复
热议问题