使用fs.readFile在Node.js中读取和返回多个文件 [英] Reading and returning multiple files in Node.js using fs.readFile

查看:464
本文介绍了使用fs.readFile在Node.js中读取和返回多个文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个简单的请求处理程序以返回一对CSS文件.使用fs.readFileSync,这很容易.但是,使用异步版本的readFile很难完成相同的任务.下面是我的代码.将我的response.write()方法调用拆分到两个不同的回调中似乎是有问题的.有人可以指出我做错了什么吗?有趣的是,如果我将response.end()放在第一个else语句中,则此代码有效.但是,这产生了一个问题,即第二个css文件没有返回(因为response.end()已被触发).

I'm writing a simple request handler to return a pair of css files. Using fs.readFileSync this was easy. However, I'm having difficulty accomplishing the same task using the async version of readFile. Below is my code. Having my response.write() method calls split among two different callbacks seems to be problematic. Can someone point out what I've done wrong? Interestingly this code works if I put response.end() inside of the first else statement. However, that creates a problem in that the second css file does not get returned (because response.end() has already been fired).

function css(response) {

  response.writeHead(200, {"Content-Type": "text/css"});

  fs.readFile('css/bootstrap.css', function(error, content){
    if(error){
      console.log(error);
    }
    else{
      response.write(content);
    }
  });
  fs.readFile('css/bootstrap-responsive.css', function(error, content){
    if(error){
      console.log(error);
    }
    else{
      response.write(content)
    }
  });
  response.end();
}

推荐答案

您所拥有的主要问题是response.end()立即被调用.您只需在文件完成其response.write调用后调用它.

The primary issue with what you have is that response.end() gets called right away. You need to only call it after the files have done their response.write calls.

最简单的方法是使用控制流库.通常,管理多个异步回调很复杂.

The easiest way would be to use a control flow library. Managing multiple asynchronous callbacks is generally complicated.

https://github.com/joyent/node/wiki/modules#wiki-async-flow

我将使用 async 库,因为它是我最了解的库.

I'm going to use the async library because it's the one I know best.

var fs = require('fs');
var async = require('async');

function css(response) {
  response.writeHead(200, {"Content-Type": "text/css"});

  async.eachSeries(
    // Pass items to iterate over
    ['css/bootstrap.css', 'css/bootstrap-responsive.css'],
    // Pass iterator function that is called for each item
    function(filename, cb) {
      fs.readFile(filename, function(err, content) {
        if (!err) {
          response.write(content);
        }

        // Calling cb makes it go to the next item.
        cb(err);
      });
    },
    // Final callback after each item has been iterated over.
    function(err) {
      response.end()
    }
  );
}

如果您想在没有库的情况下完成此操作,或者只是想用另一种方式,这就是我将更直接地做到这一点的方法.基本上,您保留count并在两个文件读取完成后调用end.

If you want to accomplish this without a library, or just want another way, this is how I would do it more directly. Basically you keep a count and call end once both file reads have finished.

function css(response) {
  response.writeHead(200, {"Content-Type": "text/css"});

  var count = 0;
  var handler = function(error, content){
    count++;
    if (error){
      console.log(error);
    }
    else{
      response.write(content);
    }

    if (count == 2) {
      response.end();
    }
  }

  fs.readFile('css/bootstrap.css', handler);
  fs.readFile('css/bootstrap-responsive.css', handler);
}

这篇关于使用fs.readFile在Node.js中读取和返回多个文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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