Node.js Nodejs流式上载多个文件
我正在开发一个命令行应用程序,它应该包含一个文件名数组, 执行转换操作(文本文件、电子表格等有效负载必须重写为JSON对象),并将结果发送到端点API(API.example.com)。 我正在考虑一个顺序读取,并将结果传递到-http或-request的实例, 但不知道从哪里开始。你有没有其他方法或策略来解决类似的问题 任何算法,或指向一篇文章或类似的问题在这里,所以将高度赞赏。 谢谢 更新1。我在这个谷歌群组中找到了一个可能有用的链接 要跟踪最终解决方案,请执行以下操作:Node.js Nodejs流式上载多个文件,node.js,file,stream,node-request,Node.js,File,Stream,Node Request,我正在开发一个命令行应用程序,它应该包含一个文件名数组, 执行转换操作(文本文件、电子表格等有效负载必须重写为JSON对象),并将结果发送到端点API(API.example.com)。 我正在考虑一个顺序读取,并将结果传递到-http或-request的实例, 但不知道从哪里开始。你有没有其他方法或策略来解决类似的问题 任何算法,或指向一篇文章或类似的问题在这里,所以将高度赞赏。 谢谢 更新1。我在这个谷歌群组中找到了一个可能有用的链接 要跟踪最终解决方案,请执行以下操作: var reque
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”是高-100个文本文件或更多,如何使其适用于“n”文件。尝试并出错后,我用事件解决了这个问题,并粘贴答案,以防其他人正在努力解决类似问题
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 ... ');
注意:
- 为了快速测试
- 我用get进行快速测试,但post/put也可以。 我希望它能有所帮助,请随意发表评论。谢谢