我正在研究一个命令行应用程序,该应用程序应该采用文件名数组,进行转换操作(文本文件,电子表格等有效负载必须重写为JSON对象),并将结果发送到端点API (api.example.com)。我正在考虑顺序读取,并将结果管道到-http或-request的实例,但不知道从哪里开始。对于类似的问题,你有没有其他的解决方法或策略?
任何算法,或指出一篇文章或类似的问题在这里将非常感谢。谢谢。
Update1。我发现了一个链接,可能会帮助在这个谷歌组https://groups.google.com/forum/#!主题/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文本文件或更多的情况下。
在尝试和错误之后,我用Events解决了这个问题,并且我粘贴了答案,以防其他人正在努力解决类似的问题。
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也可以。希望能有所帮助,欢迎留言。谢谢。