将stdin与守护程序过程使用



我有一个需要运行24/7的脚本,因此我一直在使用PM2运行它。但是,我也希望偶尔检查脚本。在作为守护程序运行之前,我将其设置为阅读stdin,但是对于守护程序而言,这不起作用。有没有简单的方法来执行此操作并运行守护程序?

我知道这与守护程序的性质相矛盾,但是我需要脚本连续运行并且用户输入有限。

可以通过使用process.spawn完成以下示例,取自本书:Professional node.js

创建一个名为plus_one.js的文件:

// unpause the stdin stream 
process.stdin.resume(); 
process.stdin.on('data', function(data) {
var number; 
try {
  // parse the input data into a number 
  number = parseInt(data.toString(), 10);
  // increment by one 
  number += 1;
  // output the number
  process.stdout.write(number + "n"); 
 } catch(err) {
    process.stderr.write(err.message + "n"); 
 }
});

您可以通过致电以下方式运行此简单程序:

$ node plus_one.js

创建一个名为plus_one_test.js的文件:

var spawn = require('child_process').spawn;
// Spawn the child with a node process executing the plus_one app var 
child = spawn('node', ['plus_one.js']);
// Call this function every 1 second (1000 milliseconds): 
setInterval(function() {
// Create a random number smaller than 10.000 
  var number = Math.floor(Math.random() * 10000);
// Send that number to the child process: 
  child.stdin.write(number + "n");
// Get the response from the child process and print it: 
  child.stdout.once('data', function(data) {
    console.log('child replied to ' + number + ' with: ' + data); 
  });
}, 1000);
child.stderr.on('data', function(data) { 
  process.stdout.write(data);
});

在这里,您可以在第1至4行上启动 1应用程序作为子进程。然后,您使用setInterval函数每秒执行以下操作:创建一个小于10,000的随机天然数字。将该号码作为字符串发送到子过程。等待子过程用字符串回复。

最新更新