简体   繁体   English

永远运行节点脚本

[英]Run node script forever

I'm writting an app which is waiting for message and then will do some action. 我正在编写一个正在等待消息的应用程序,然后将执行一些操作。 Messages are receiving through the Redis channel. 邮件正在通过Redis通道接收。 So, i need nodejs script to be running infinitely (as i understand) 因此,我需要nodejs脚本无限运行(据我了解)

How can i make it run without starting node server (i feel like it is wrong to start the server for such a simple task). 我如何在不启动节点服务器的情况下使其运行(我觉得对于这样一个简单的任务启动服务器是错误的)。

Code: 码:

const redis = require("redis")
const subscriber = redis.createClient()
const http = require('http');

const hostname = '127.0.0.1';
const port = 3002;

subscriber.on("message", (channel, message) => {
  console.log(Buffer.from(message, 'base64'));
})

subscriber.subscribe('test')

// Server code, which i was using to start infinity loop
//
// const server = http.createServer((req, res) => {
//   res.statusCode = 200;
//   res.setHeader('Content-Type', 'text/plain');
//   res.end('Hello World\n');
// });
//
// server.listen(port, hostname, () => {
//   console.log(`Server running at http://${hostname}:${port}/`);
// });

subscriber.js Subscriber.js

 const redis = require("redis"); const subscriber = redis.createClient(); const hostname = '127.0.0.1'; const port = 6379; subscriber.on("message", function(channel, message) { console.log(message); }); subscriber.subscribe('test'); 

publisher.js Publisher.js

 const redis = require("redis"); const publisher = redis.createClient(); const hostname = '127.0.0.1'; const port = 6379; publisher.publish('test',"Hello I am Here !!!"); 

This is an Example Code for both publisher and subscriber.No need to run an HTTP server to subscribe from redis. 这是发布者和订阅者的示例代码。无需运行HTTP服务器即可从redis进行订阅。 You just want to keep run subscriber.js . 您只想继续运行Subscriber.js。

If this channel is inactive for a particular day channel goes to sleep state.So all other messages are may be lost. 如果该频道在特定的一天中处于非活动状态,则该频道会进入睡眠状态,因此所有其他消息可能会丢失。

If you want to avoid this,you need to run a scheduler script to publish a dummy message to your channel for particular day (May be per day once) 如果您想避免这种情况,则需要运行调度程序脚本以在特定日期(可能每天一次)向您的频道发布虚拟消息。

You can use forever npm module to run your node continuously. 您可以使用永远的npm模块来连续运行节点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM