从fs.readFile获取数据 [英] Get data from fs.readFile

查看:572
本文介绍了从fs.readFile获取数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

记录 undefined ,为什么?

推荐答案

要详细说明@Raynos所说的内容,您定义的函数是异步回调。它不会立即执行,而是在文件加载完成时执行。当您调用readFile时,将立即返回控件并执行下一行代码。因此,当您调用console.log时,尚未调用您的回调,并且尚未设置此内容。欢迎使用异步编程。

To elaborate on what @Raynos said, the function you have defined is an asynchronous callback. It doesn't execute right away, rather it executes when the file loading has completed. When you call readFile, control is returned immediately and the next line of code is executed. So when you call console.log, your callback has not yet been invoked, and this content has not yet been set. Welcome to asynchronous programming.

示例方法

const fs = require('fs');
var content;
// First I want to read the file
fs.readFile('./Index.html', function read(err, data) {
    if (err) {
        throw err;
    }
    content = data;

    // Invoke the next step here however you like
    console.log(content);   // Put all of the code here (not the best solution)
    processFile();          // Or put the next step in a function and invoke it
});

function processFile() {
    console.log(content);
}

或者更好,正如Raynos示例所示,将您的呼叫包裹在一个函数中传递你自己的回调。 (显然这是更好的做法)我认为习惯在函数中包装你的异步调用需要回调将为你节省很多麻烦和杂乱的代码。

Or better yet, as Raynos example shows, wrap your call in a function and pass in your own callbacks. (Apparently this is better practice) I think getting into the habit of wrapping your async calls in function that takes a callback will save you a lot of trouble and messy code.

function doSomething (callback) {
    // any async callback invokes callback with response
}

doSomething (function doSomethingAfter(err, result) {
    // process the async result
});

这篇关于从fs.readFile获取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆