gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 22:10:24 26 4
gpt4 key购买 nike

我正在编写一个简单的请求处理程序来返回一对 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com