How to update server contents without restarting? (node.js)

So, I have a simple node.js server that only serves dynamic content:

// app.js
var app = require('express')();

app.get('/message/:poster', function(request, response) {
    response.writeHeader(200, {'content-type': 'text/html'});

    // some database queries

    response.end(""+
    "<!DOCTYPE html>"+
    "<html>"+
        "<head>"+
            "<title>messages of "+request.params.poster+"</title>"+
            "<script src='http://example.com/script.js'></script>"+
            "<link rel='stylesheet' href='http://example.com/style.css'>"+
        "</head>"+
        "<body>"+
        "" // and so on
    );
})

app.listen(2345);

Now suppose I want to update my HTML.
And suppose I do not want to restart the server.
Is there any way to achieve this?

I tried to export the part to send to an external file, for example:

// lib.js
module.exports.message = function(request, response) {
    response.writeHeader(200, {'content-type': 'text/html'})

    //some database queries

    response.end(""+
    "<!DOCTYPE html>"+
    "<html>"+
        "<head>"+
            "<title>messages of "+request.params.poster+"</title>"+
            "<script src='http://example.com/script.js></script>"+
            "<link rel='stylesheet' href='http://example.com/style.css'>"+
        "</head>"+
        "<body>"+
        "" //and so on
    );
}

and

// app.js
var app = require('express')();

app.get('/message/:poster', require('./lib.js').message)

app.listen(2345);

And it works, but if I update lib.js, it does not update. This seems to be a copy of this feature.
Then i tried

// app.js
var app = require('express')();

app.get('/message/:poster', function(request, response) {
    require('./lib.js').message(request, response);
})

app.listen(2345);

.
, ( ). , , (, , ), , n , node, , , , , .
, ? - ? , 100 , -, .
. , jade, ejc ..

+4
4

- - , PM2, Forever .. - Nodemon. , .

+1

. , , lib.js .

What you are looking for is a way to hot load node.js modules to get a new instance of the module every time it changes. You can use node-hotswap

require('hotswap');

and for any module you want to track changes:

module.change_code = 1;
0
source

Could you just use the read / write API for nodejs?

http://nodejs.org/api/fs.html

Request-> ReadFile-> Send content to client

At least for static content like html.

0
source

All Articles