节点js http服务器请求体作为流可读 [英] node js http server request body as stream readable

查看:204
本文介绍了节点js http服务器请求体作为流可读的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用node.js编写一个http服务器,并且无法将请求主体隔离为流可读。以下是我的代码的基本示例:

I'm writing a http server using node.js and having trouble isolating the request body as a stream readable. Here is a basic sample of my code:

var http = require('http')
  , fs = require('fs');

http.createServer(function(req, res) {
  if ( req.method.toLowerCase() == 'post') {
    req.pipe(fs.createWriteStream('out.txt'));
    req.on('end', function() {
      res.writeHead(200, {'content-type': 'text/plain'})
      res.write('Upload Complete!\n');
      res.end();
    });
  }
}).listen(8182);
console.log('listening on port 8182');

根据节点的文档 a request param是http.IncomingObject的一个实例,它实现了节点的可读流接口。像我上面一样使用stream.pipe()的问题是可读流包括请求标头的纯文本以及请求主体。有没有办法将请求主体隔离为可读流?

According to node's documentation the a request param is an instance of http.IncomingObject which implements node's readable stream interface. The problem with just using stream.pipe() as I did above is the readable stream includes the plain text of the request headers along with the request body. Is there a way to isolate only the request body as a readable stream?

我知道存在文件上传的框架,例如强大的。我的最终目标不是创建上传服务器,而是充当代理并将请求主体流式传输到另一个Web服务。

I'm aware that there are frameworks for file uploads such as formidable. My ultimate goal is not to create an upload server but to act as a proxy and stream the request body to another web service.

提前感谢。

编辑>>
工作服务器内容类型:multipart / form-data使用busboy

Edit>> working server for "Content-type: multipart/form-data" using busboy

var http = require('http')
  , fs = require('fs')
  , Busboy = require('busboy');

http.createServer(function(req, res) {
  if ( req.method.toLowerCase() == 'post') {
    var busboy = new Busboy({headers: req.headers});
    busboy.on('file', function(fieldname, file, filename, encoding, mimetype) {
      file.pipe(fs.createWriteStream('out.txt'));
    });
    req.pipe(busboy);
    req.on('end', function() {
      res.writeHead(200, 'Content-type: text/plain');
      res.write('Upload Complete!\n');
      res.end();
    });
  }
}).listen(8182);
console.log('listening on port 8182');


推荐答案

检查 req.headers [ '内容 - 类型'] 。如果它是 multipart / form-data 那么您可以使用像这样的模块busboy 为您解析请求,并为您提供文件部分的可读流(如果存在,则为非文件部分的简单字符串)。

Check your req.headers['content-type']. If it's multipart/form-data then you could use a module like busboy to parse the request for you and give you readable streams for file parts (and plain strings for non-file parts if they exist).

如果content-type是其他一些 multipart / * 类型,那么你可以使用 dicer ,这是busboy用于解析多部分的底层模块。

If the content-type is some other multipart/* type, then you could use dicer, which is the underlying module that busboy uses for parsing multipart.

这篇关于节点js http服务器请求体作为流可读的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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