[英]Keep order in nodejs command line script
我想在nodejs中进行编码,但是我对如何实现它一无所知。 我已经阅读和搜索了很多东西,但仍然不知道什么是正确的方法。
问题如下:
您不能先读取“所有”文件,然后再分割行:您必须一次处理一行,记住它是标准输入。 您不知道输入何时结束。
有人对如何解决这个问题有一些线索吗? 我不知道如何进行。
您可以执行以下操作:
const http = require('http'); const Promise = require('bluebird'); let arrayOfRequests = []; process.stdin.on('data', (data) => { //get data from the stdin //then add the request to the array arrayOfRequests.push(http.get({})) }) process.stdin.on('end', () => { Promise.all(arrayOfRequests) // use Promise .all to bundle all of the reuqest //then use the spread operator so you can use all of the reuqest In order .spread( (request1,request2,request3) => { // do stuff }) })
仅供参考,摘要无法正常工作。
因此,您正在使用内置在Node.js中的process.stdin
。 然后,您将捆绑所有请求。 每当用户取消该程序时,就会发出您的请求。 由于调用将是异步的,因此可以将它们放在数组中,然后运行Promsise.all
并使用bluebird
.spread
运算符解构Promise.all
并获取值。
到目前为止,我已经为nodejs中的生产者-消费者问题提供了该解决方案,在这种情况下,生产者在队列中没有可用空间之前不会产生更多数据。
这是基于块队列的队列代码: https : //gist.github.com/AlvaroMaceda/8a933a317fed3fd4691fd5eda3e60c5e
要使用阻塞队列,请使用3个参数创建它:
仅当需要更多数据时,队列才会调用“推送”。 例如,如果有五个正在运行的任务,并且创建时最多包含五个并发任务,则在这些任务之一结束之前,不会调用“ push”。
这是一个如何使用它的示例:
"use strict";
const queue = require('./block-queue');
const CONCURRENCY = 5;
const WORKS_TO_LAUNCH = 10;
const TIMEOUT = 200;
let i = 1;
let q = queue(CONCURRENCY, doSomethingAsync, putMoreData );
function putMoreData(queue) {
if (++i <= WORKS_TO_LAUNCH) {
console.log('Pushing to queue');
queue.push(i);
}
}
function doSomethingAsync(task, done) {
setTimeout(function() {
console.log('done ' + task);
done();
}, 1000 + task * TIMEOUT);
}
q.push(i);
我没有解决这个问题,因为我不知道是否有更简单的方法,并且我想使用完整的解决方案,也不知道在使用此方法和流时是否会发现一些问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.