是否可以将流从一个功能转发到另一个功能?

时间:2014-10-08 14:19:52

标签: javascript node.js stream form-data busboy

请查看以下示例代码。

如您所见,它使用busboy来解析传入的表单数据并将传入的文件写入光盘。 我们假设这些只是图像文件,因为我的示例代码使用了imgur.com。 (不需要发送内容长度标题) imgurUpload()函数使用node-form-data

以某种方式可以将图像文件另外流式传输到imgur.com,而无需将它们缓冲完整。 (到imgurUpload()函数并在node-form-data中使用它?)

服务器/监听器:

var http = require('http'),
  Busboy = require('busboy'),
  FormData = require('form-data'),
  fs = require('fs')

http.createServer(function(req, res) {
  if (req.method === 'POST') {
    var busboy = new Busboy({
      headers: req.headers
    })
    busboy.on('file', function(fieldname, file, filename, encoding, mimetype) {
      //pipe the stream to disc
      file.pipe(fs.createWriteStream('1st-' + filename))
      //pipe the stream a 2nd time
      file.pipe(fs.createWriteStream('2nd-' + filename))

      /* how to connect things together? */
    })
    busboy.on('finish', function() {
      res.writeHead(200, {
        'Connection': 'close'
      })
      res.end("upload complete")
    })
    return req.pipe(busboy)
  } else if (req.method === 'GET') {
    var stream = fs.createReadStream(__dirname + '/index.html')
    stream.pipe(res)
  }
}).listen(80, function() {
  console.log('listening for requests')
})

HTML测试表单(index.html)

<!doctype html>
<head></head>
<body>
  <form action="/upload" method="post" enctype="multipart/form-data">
    <input type="file" name="file">
    <input type="submit" value="submit">
  </form>
</body>
</html>

将图像文件提交到imgur.com的示例函数:

function imgurUpload(stream) {

  var form = new FormData()
  //form.append('Filedata', fs.createReadStream('test.jpg'))

  form.append('Filedata', /* how to connect things together? */X )
  form.submit('http://imgur.com/upload', function(err, res) {
    if (err) throw err

    var body = ''
    res.on('data', function(chunk) { body += chunk })
    res.on('end', function() { console.log('http://imgur.com/' + JSON.parse(body).data.hash) })
  })
}

更新(关于mscdex回答)

_stream_readable.js:748
    throw new Error('Cannot switch to old mode now.');
          ^
Error: Cannot switch to old mode now.
    at emitDataEvents (_stream_readable.js:748:11)
    at FileStream.Readable.pause (_stream_readable.js:739:3)
    at Function.DelayedStream.create (\path\node_modules\form-data\node_modules\combined-stream\node_modules\delayed-stream\lib\delayed_stream.js:35:12)
    at FormData.CombinedStream.append (\path\node_modules\form-data\node_modules\combined-stream\lib\combined_stream.js:45:30)
    at FormData.append (\path\node_modules\form-data\lib\form_data.js:43:3)
    at imgurUpload (\path\app.js:54:8)
    at Busboy.<anonymous> (\path\app.js:21:4)
    at Busboy.emit (events.js:106:17)
    at Busboy.emit (\path\node_modules\busboy\lib\main.js:31:35)
    at PartStream.<anonymous> (\path\node_modules\busboy\lib\types\multipart.js:205:13)

1 个答案:

答案 0 :(得分:1)

您可以附加可读流,如node-form-data自述文件中所示。所以这个:

form.append('Filedata', stream);

应该可以正常工作。

然后在你的file事件处理程序中:

imgurUpload(file);