Nodejs流上传多个文件

时间:2014-08-24 17:15:08

标签: node.js file stream node-request

我正在开发一个应该采用文件名数组的命令行应用程序, 转换操作(文本文件,电子表格等有效负载必须重写为JSON对象),并将结果发送到端点API(api.example.com)。 我正在考虑顺序读取,并将管道结果发送到-http或-request的实例, 但不知道从哪里开始。您是否有任何替代方案或策略用于解决类似的问题?

任何算法,或指向SO上的文章或类似问题都将受到高度赞赏。 感谢。

UPDATE1。我找到了一个可能有助于此Google论坛https://groups.google.com/forum/#!topic/nodejs/_42VJGc9xJ4

的链接

跟踪最终解决方案:

var request = require('request');
var file = fs.createReadStream(path)
      .pipe(request.put({url: url, headers:{'Content-Length': fileSize}}, function(err, res, body){
        if(err) {
          console.log('error', err);
        } else {
          console.log('status', res.statusCode);
          if(res.statusCode === 200) {
            console.log('success'); 
          }
        }
      }));

剩下的问题是如何为" n"文件,如果" n"高 - 100个文本文件或更多。

1 个答案:

答案 0 :(得分:0)

在尝试和错误之后,我用事件解决了这个问题,并且我粘贴答案以防万一其他人正在努力解决类似的问题。

var EventEmitter = require('events').EventEmitter;
var request        = require('request');
var util          = require('util');


function Tester(){
  EventEmitter.call(this);
  this.files = ['http://google.ca', 'http://google.com', 'http://google.us'];



}

util.inherits( Tester, EventEmitter );

Tester.prototype.run = function(){
  //referencing this to be used with the kids down-here  
  var self = this;
  if( !this.files.length ) { console.log("Cannot run again .... "); return false; }
  request({ url : this.files.shift()}, function( err, res, body ) {
    console.log( err, res.statusCode, body.length, " --- Running the test --- remaining files ", self.files );
    if( !self.files.length ) self.emit( "stop" );
    else self.emit( "next" , self.files );
  });
};

//creating a new instance of the tester class
var tester = new Tester();
  tester.on("next", function(data){
       //@todo --- wait a couple of ms not to overload the server.
       //re-run each time I got this event
       tester.run();
  });
  tester.on("stop", function(data){
    console.log("Got stop command --- Good bye!");
  });
  //initialize the first run
  tester.run();
  //graceful shutdown -- supporting windows as well 
  //@link http://stackoverflow.com/questions/10021373/what-is-the-windows-equivalent-of-process-onsigint-in-node-js
  if (process.platform === "win32") {
    require("readline").createInterface({
        input: process.stdin,
        output: process.stdout
    }).on("SIGINT", function () {
        process.emit("SIGINT");
    });
}

process.on("SIGINT", function () {
    // graceful shutdown
    process.exit();
});



console.log('Started the application ... ');

NB:

  • 快速测试here is the runnable

  • 我用get进行快速测试,但post / put也可以。 我希望它有所帮助,随时发表评论。感谢。