是否可以将流从一个函数转发到另一个函数



请查看以下示例代码。

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

是否可以以某种方式将图像文件额外流式传输到imgur.com,而无需对其进行完整缓冲?(到imgurUpload()函数,并在节点表单数据中使用它?)

服务器/侦听器:

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 (pathnode_modulesform-datanode_modulescombined-streamnode_modulesdelayed-streamlibdelayed_stream.js:35:12)
    at FormData.CombinedStream.append (pathnode_modulesform-datanode_modulescombined-streamlibcombined_stream.js:45:30)
    at FormData.append (pathnode_modulesform-datalibform_data.js:43:3)
    at imgurUpload (pathapp.js:54:8)
    at Busboy.<anonymous> (pathapp.js:21:4)
    at Busboy.emit (events.js:106:17)
    at Busboy.emit (pathnode_modulesbusboylibmain.js:31:35)
    at PartStream.<anonymous> (pathnode_modulesbusboylibtypesmultipart.js:205:13)

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

form.append('Filedata', stream);

应该还可以。

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

imgurUpload(file);

相关内容

  • 没有找到相关文章

最新更新