如何提供使用fs.readFile读取的文件 [英] How to serve a file read with fs.readFile

查看:669
本文介绍了如何提供使用fs.readFile读取的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用nodejs开发应用程序。我必须读取服务器上的本地文件,我正在使用此功能:

i'm developing an application with nodejs. I have to read a local file on server, i'm using this function:

fs.readFile(path, "utf8", function (err,data) {}

我如何为客户提供数据?最好在新选项卡中打开它或将其下载到客户端上。

how i can serve the 'data' to client? is good to open it in a new tab or downloading it on client.

-更新-
我也正在尝试使用此解决方案。是一个好方法吗?

--UPDATE-- I'm trying to use this solution, too.. is a good way?

res.writeHead(200, {"Content-Type": "application/pdf"});
res.write(data);
res.end();


推荐答案

假定您在此处使用某种HTTP服务器,则在处理程序中将收到一个 response 对象。我在这里使用内置节点HTTP服务器。

Assuming you're using some sort of HTTP server here, you'll receive a response object in the handler. This object is actually a stream. I'm using the built-in node HTTP server here for my example.

http.createServer(function(req, res){
    fs.createReadStream(path).pipe(res);
});

表达式 hapi 如果使用的是以下特定的发送文件响应类型:

In express and hapi there is a specific send-file response type if you're using those:

Hapi: reply.file

快递: res.sendFile

这篇关于如何提供使用fs.readFile读取的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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