I'm trying to run a really simple implementation of a Node JS server using Express to serve EJS content. When I start the server and it runs perfectly fine, but then unexpectedly crashes after a while. Sometimes it will crash within a half an hour, while other times it has stayed up for 4-6 hours at a time.
I can't seem to pin down a source of the error because my logs do not contain any stack traces.
I've taken this answer's advice and I have this:
process.on('uncaughtException', function (exception) {
console.log(exception); // to see your exception details in the console
});
and I've also overloaded the console
methods to log to a file, like so:
console.log = function(d) {
log(d);
};
console.error = function(d) {
log(d);
};
function log(message) {
log_file.write(util.format(message) + '\n');
log_stdout.write(util.format(message) + '\n');
}
Still, the server crashes without reporting anything. I've also tried to create a Node domain
:
var domain = require('domain');
var d = domain.create();
d.on('error', function(err) {
console.error(err);
});
If I had to take a guess, I would imagine this error might be caused by the process running out of memory, as I am running all of this on the Raspberry Pi model B version 2, but I can't be sure. If it was truly running out of memory, I would expect to see:
FATAL ERROR: JS Allocation failed - process out of memory
reported somewhere in my logs.
My server itself is actually quite simple:
// Create Express and set up the EJS view engine
var app = express();
app.set('view engine', 'ejs');
app.use("/resources", express.static(__dirname + "/resources"));
// Setup the index page view
app.get('/', function(req, res) {
console.log(getFormattedDate() + req.method + " " + req.url + " by " + req.connection.remoteAddress);
res.render('pages/index', {
title: "James Taylor",
content: formattedContent
});
});
app.get('*', function(req, res, next) {
var err = new Error();
err.status = 404;
next(err);
});
app.use(function(err, req, res, next) {
if (err.status == 404) {
console.error(getFormattedDate() + err + req.url);
res.set("Content-Type", "text/plain");
res.status(err.status);
res.send(err.message);
} else {
console.error(err);
return next();
}
});
In the meantime, I've been able to get around this issue by using forever, which seems to work nicely.
I'd appreciate any advice you could give about trying to troubleshoot this problem. It just doesn't seem right that I have to have all this infrastructure surrounding a perpetually crashing server.