node.js - 使用 fs.readFile 在 Node.js 中读取和返回多个文件

标签 node.js

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

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 调用后调用它。

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

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

我将使用 async图书馆,因为它是我最了解的。

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

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);
}

关于node.js - 使用 fs.readFile 在 Node.js 中读取和返回多个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9448336/

相关文章:

node.js - Sequelize 抛出 [object SequelizeInstance : tablename] error

node.js - Mongoose 查询填充查找元素的匹配 ID

node.js - 如何从 Socket.IO/Node.js 提供策略文件

javascript - 当客户端连接到服务器时,NODE.JS 中的 Async Await 失败

javascript - 在 Mongoose 查询中使用变量作为属性名称未返回正确结果

node.js - npm 脚本同时运行 redis-server、mongod 和 nodemon

javascript - 跨多个应用程序共享 mongo 模型

node.js - Mongoose - 将方法添加到回调中返回的对象

javascript - 无法在 Google Cloud Functions 中使用 ES 模块

javascript - 扩展尚未创建的 javascript (nodeJS) 对象