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

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

问题描述

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

Logs 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');
// First I want to read the file
fs.readFile('./Index.html', function read(err, data) {
    if (err) {
        throw err;
    }
    const content = data;

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

function processFile(content) {
    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天全站免登陆