如何在node.js中创build可中断的循环

免责声明:我是一个Node.js新手,下面的描述可能会很长…

我目前正试图教自己的Node.js一个小项目,我后。 项目的想法如下:RaspberryPI运行一个Node.js应用程序,它允许我控制RGB LED灯条的颜色。 应用程序应该能够设置一个静态颜色,也可以运行颜色平滑的颜色轮。

我的想法是现在创build几个Node.js脚本:

  1. 执行客户端通信的“控制器”,设置静态颜色或能够启动色轮
  2. “客户端脚本”,每个运行一个色轮。 他们中至多有一个是“活着的”,由“控制者”启动/停止,

我已经能够创build一个脚本来分叉另一个脚本,并能够使用child.send来停止脚本,如下所示:

controller.js

 var fork = require('child_process').fork, test2 = fork(__dirname + '/test2.js'); setTimeout(function() { test2.send({func: 'quit'}); }, 5000); 

这分叉了test2.js脚本,并在5秒钟之后发送退出test2.jsquit消息。

test2.js

 function runLoop() { console.log("Hello"); setTimeout(runLoop, 1000); } process.on('message', function(m) { if (m.func === 'quit') { process.exit(0); } }); setTimeout(runLoop, 1000); 

这个“客户端脚本”每秒打印“Hello”,直到控制器发送quit消息。

这工作得很好 – 5秒钟后脚本完成优雅。

我的问题是现在:如果我实现了一个色轮,我需要一个可能无限循环,改变LED灯带的颜色。 上面的(当然更短的定时器值 – 我需要10ms这样的东西)是实现可中断循环的一种可行的方式,还是有一些我还不知道的更好的机制?

你让生活变得复杂 你的全球架构如下:

 external trigger --> listener ----------> code that changes color (ie. web client) (ie. web server) 

考虑到这一点,您不需要分叉任何进程,就可以在一个进程中控制LED灯条。 在你的代码的某个地方,你会有一个类似于这样的对象:

 //"led" is the module that allows you to change the color of a led (suppose 4 leds) var led = require ("led-controller"); var ColorChanger = module.exports = function (){ this._intervalId = null; }; ColorChanger.prototype.setColor = function (hex){ //Color in hexadecimal //Cancel any current interval cancelInterval (this._intervalId); led.color (0, hex); led.color (1, hex); led.color (2, hex); led.color (3, hex); }; ColorChanger.prototype.wheel = function (hex, ms){ //Color in hexadecimal //"ms" is the time interval between leds going on and off //Cancel any current interval cancelInterval (this._intervalId); //Shutdown all the leds led.off (0); led.off (1); led.off (2); led.off (3); //Activate the first led led.color (0, hex); //Current active led var curr = 0; this._intervalId = setInterval (function (){ //Each "ms" the current led will go off and the next will go on led.off (curr); //Next led to activate curr = ++curr%4; led.color (curr, hex); }, ms); }; 

然后监听器模块使用ColorChanger

 var ColorChanger = require ("./color-changer"); var changer = new ColorChanger (); //Set all the leds to red changer.setColor ("#FF0000"); //Each 10ms one led goes green and the previous is turned off, in an endless loop changer.wheel ("#00FF00", 10); 

如果你使用setTimeout ,你甚至不需要fork一个新的进程。 以下是我将如何写你的例子:

 var ntrvl = setInterval(function() { console.log('Hello'); }, 1000); setTimeout(function() { clearInterval(ntrvl); }, 5000); 

… 很简单。 有了setTimeoutsetInterval ,你使用的是asynchronous函数,所以你不会阻塞事件循环。 当定时器启动时,它运行你的代码,然后等待下一个事件。 你应该能够控制所有的“客户端”,你将拥有比你实际需要的带宽更多的带宽,同时在同一个进程中。

所有你需要警惕的是你没有阻止脚本。 如果您尝试同步执行任何操作(这意味着脚本将在执行下一个命令之前等待操作完成),那么您需要确保它快速运行。 如果您必须同步运行处理器/时间密集型任务,那么您需要分叉一个新进程。