简体   繁体   中英

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. So, i need nodejs script to be running infinitely (as i understand)

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

 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

 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. You just want to keep run 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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