最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Issue with node.js app stopping on AWS - Stack Overflow

programmeradmin3浏览0评论

I have a node.js app that pings a url and then sends a message to Slack if it gets an error code. It works fine for two days but then it just stops working. I'm using Screen to keep it running but it still seems to stop. Any help would be greatly appreciated.

The code is below:

var request = require("request")
var Hapi = require('hapi');
var Slack = require('slack-node');
var h = 0;
var s = 0;
var e = 0;

function onlineBooking(){
request({
    url: "",
    json: true
}, function (error, response, body) {

    if (!error && response.statusCode === 200) {

        // 'if/else' checks that it receives an up respsose four times in a row 
        // the variable e is increased by .25 for every 200(ok response) until e reaches 1
        // it will then send a message that the server is up
        if(e < 1  && response.statusCode === 200){
            setTimeout(function () {
           console.log(response.statusCode) // Print the response code
            e =e+0.25;
            }, 6000); // 6 seconds delay between each response 
        }

    else {
          while(h == 0){
        console.log(response.statusCode) // Print the response code
        console.log("********************")
        slackReviewBot("Website :robot_face: ", response.statusCode + " - OK", "", "");
            h++;
            s = 0; 
          } 
        }// end of else
    }// end of if
    else {
        console.log(response.statusCode) // Print the response code
        e = 0;
        setTimeout(function () {  
        while(s == 0){

        console.log(response.statusCode) // Print the response code
        console.log("********************")
        slackReviewBot("Website :robot_face: ", response.statusCode, "", "");
            s++;
            h=0;
        }}, 3000);
    } // end of else

})

}

// sets the loop for checking every 7 seconds

setInterval(function(){

    onlineBooking();

}, 7000); 


//  this function sends server name, a message and url to slack
function slackReviewBot(servername, body, urls, bod) {

var time = require('time');
// Create a new Date instance
var now = new time.Date();
now.setTimezone("Europe/London");

    var bo = body; 
    var bod = bod;
    var urls = urls;
    var sname = servername; 
    // you'll need to replace the slack webhook below
    // you'll find info on webhooks here 
    var webhook_url = '';
    slack = new Slack();
    slack.setWebhook(webhook_url);

        slack.webhook({
        channel: "#server-uptime",
        username: "Server:",
        icon_emoji: ".png",
        text: " " + "\n" + 
            "*" + sname + " * " + "\n" +
            "Status: " + bo + "\n" +
            now + "\n" +
            "Check the status here: " + urls + "\n" 

        }, function(err, response) {      
        console.log(response);
        }); 
}



// below is so you can send a test json object to the server
// http POST localhost:1337/jsonpost test=Test 
// you'll get a slack message letting you know the server is running
var server = new Hapi.Server();
server.connection({
    port: 1337
});

exports.add = function(i, j) {
    return i + j;
};

//  Slack function for sending the test reply
function slackReviewBot2(testserver) {
    testserver = testserver;
      // you'll need to replace the slack webhook below
    // you'll find info on webhooks here 
    var webhook_url = '';
    slack2 = new Slack();
    slack2.setWebhook(webhook_url);


        slack.webhook({
        channel: "#server-uptime",
        username: "Server-Test-Reply:",
        icon_emoji: ".png",
        text: ":star: :star: :star: :star: :star:" + "\n" + 
            "\n" + 
            "Sever is up and running!!!"

        }, function(err, response) {

        console.log(response);
        });
}


// take the json object for testing
server.route({
  method: 'POST'
, path: '/jsonpost',
handler: function(req, reply) {

     var review = {
      userName: req.payload.userName
      }
            //passes the review to the slackbot function 
            slackReviewBot2(review.userName);
            reply("Received");
    } 
});

// prints a server running message 
server.start(function(){
    console.log('server running at: ', server.info.url);
});

You can find a post explaining how it works below .php

I have a node.js app that pings a url and then sends a message to Slack if it gets an error code. It works fine for two days but then it just stops working. I'm using Screen to keep it running but it still seems to stop. Any help would be greatly appreciated.

The code is below:

var request = require("request")
var Hapi = require('hapi');
var Slack = require('slack-node');
var h = 0;
var s = 0;
var e = 0;

function onlineBooking(){
request({
    url: "http://example.",
    json: true
}, function (error, response, body) {

    if (!error && response.statusCode === 200) {

        // 'if/else' checks that it receives an up respsose four times in a row 
        // the variable e is increased by .25 for every 200(ok response) until e reaches 1
        // it will then send a message that the server is up
        if(e < 1  && response.statusCode === 200){
            setTimeout(function () {
           console.log(response.statusCode) // Print the response code
            e =e+0.25;
            }, 6000); // 6 seconds delay between each response 
        }

    else {
          while(h == 0){
        console.log(response.statusCode) // Print the response code
        console.log("********************")
        slackReviewBot("Website :robot_face: ", response.statusCode + " - OK", "http://example.", "");
            h++;
            s = 0; 
          } 
        }// end of else
    }// end of if
    else {
        console.log(response.statusCode) // Print the response code
        e = 0;
        setTimeout(function () {  
        while(s == 0){

        console.log(response.statusCode) // Print the response code
        console.log("********************")
        slackReviewBot("Website :robot_face: ", response.statusCode, "http://example.", "");
            s++;
            h=0;
        }}, 3000);
    } // end of else

})

}

// sets the loop for checking every 7 seconds

setInterval(function(){

    onlineBooking();

}, 7000); 


//  this function sends server name, a message and url to slack
function slackReviewBot(servername, body, urls, bod) {

var time = require('time');
// Create a new Date instance
var now = new time.Date();
now.setTimezone("Europe/London");

    var bo = body; 
    var bod = bod;
    var urls = urls;
    var sname = servername; 
    // you'll need to replace the slack webhook below
    // you'll find info on webhooks here https://api.slack./ining-webhooks
    var webhook_url = 'https://hooks.slack./services/xxxxxxxxxxxxxxxxxxxxxx';
    slack = new Slack();
    slack.setWebhook(webhook_url);

        slack.webhook({
        channel: "#server-uptime",
        username: "Server:",
        icon_emoji: "http://4.bp.blogspot./-mYCTaPOu-60/VK98X5CJEyI/AAAAAAAAApM/0oplbclvnUY/s1600/unnamed.png",
        text: " " + "\n" + 
            "*" + sname + " * " + "\n" +
            "Status: " + bo + "\n" +
            now + "\n" +
            "Check the status here: " + urls + "\n" 

        }, function(err, response) {      
        console.log(response);
        }); 
}



// below is so you can send a test json object to the server
// http POST localhost:1337/jsonpost test=Test 
// you'll get a slack message letting you know the server is running
var server = new Hapi.Server();
server.connection({
    port: 1337
});

exports.add = function(i, j) {
    return i + j;
};

//  Slack function for sending the test reply
function slackReviewBot2(testserver) {
    testserver = testserver;
      // you'll need to replace the slack webhook below
    // you'll find info on webhooks here https://api.slack./ining-webhooks
    var webhook_url = 'https://hooks.slack./services/xxxxxxxxxxxxxxxxxxxxxxxxxx';
    slack2 = new Slack();
    slack2.setWebhook(webhook_url);


        slack.webhook({
        channel: "#server-uptime",
        username: "Server-Test-Reply:",
        icon_emoji: "http://www.wonderfulwebsites.ie/logo.png",
        text: ":star: :star: :star: :star: :star:" + "\n" + 
            "\n" + 
            "Sever is up and running!!!"

        }, function(err, response) {

        console.log(response);
        });
}


// take the json object for testing
server.route({
  method: 'POST'
, path: '/jsonpost',
handler: function(req, reply) {

     var review = {
      userName: req.payload.userName
      }
            //passes the review to the slackbot function 
            slackReviewBot2(review.userName);
            reply("Received");
    } 
});

// prints a server running message 
server.start(function(){
    console.log('server running at: ', server.info.url);
});

You can find a post explaining how it works below http://codingyoda./slack-pinging-tool.php

Share Improve this question edited May 17, 2018 at 23:03 Derek MC asked Jul 6, 2017 at 22:53 Derek MCDerek MC 3762 gold badges6 silver badges25 bronze badges 2
  • 1 Is there any log information from the node process when it fails? There are Slack API rate limits so possibly you aren't dealing with a HTTP 500 error from Slack and by the time you catch that the script has died the rate limit window has expired making the script look like it is running just fine when you restart it – Jason Sperske Commented Jul 10, 2017 at 22:50
  • 1 You need to check the error log and show it. – HuyTran Commented Jul 17, 2017 at 9:21
Add a ment  | 

2 Answers 2

Reset to default 7 +25

i dont know why this happens, but you can fix this using forever it will restart the process if bees inactive or crashes (this replaces the screen).

A log would definitely help us get to the root cause here - please do check your logs and post here. As other answers suggest - any production environment I would remend the use of forever or PM2 to restart your app if it dies. As @sebastian suggests that might fix the problem if not the cause - by auto-restarting your app. Another benefit is that these apps will log your console messages to file - which will give you (and us) a better idea of what's going on.

One more thought: you may be dealing with an uncaught exception. If you think this is happening you could add a bit of code to catch, report and even shutdown gracefully. George Ornbo wrote a great article on this here that I'd remend you read when considering what to do with these exceptions.

Here's an overly-simplified code sample to catch uncaught exceptions that should capture the error and more importantly the stack-trace that you'll need to track down where the problem originates (assuming you capture those logs):

//catches uncaught exceptions
process.on('uncaughtException', function (err) {
    console.trace("Uncaught Exception", err);
    gracefulShutdown(err);
});

// implementation beyond the scope of this question. 
function gracefulShutdown(error) {
    process.exit(error);
} 

I hope that helps!

发布评论

评论列表(0)

  1. 暂无评论