Monday 29 May 2017

Simple nodejs example with multiple files

I wrote very simple project on NodeJS. I want to make similarity to other language programming example, such as java. So I make: server.js, main.js and module (calc.js). Here are their code:

File server.js

var main = require('./main');

var http = require('http');
http.createServer(function(req, res){
    main.main(req, res);
}).listen(8080, '127.0.0.1');
console.log('Server running at http://127.0.0.1:8080/');

File main.js

var calc = require('./calc');

exports.main = function(req, res){
    var a = 5;
    var b = 9;
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end(calc.Plus(a,b));
    res.end(calc.Minus(a,b));
};

File calc.js

(function(){
    module.exports.Plus = function(a, b){
        return a+b;
    };

    module.exports.Minus = function(a, b){
        return a-b;
    };
}());

I run it on my server, and I got an error:

Server running at http://127.0.0.1:8080/ events.js:160 throw er; // Unhandled 'error' event ^

Error: listen EADDRINUSE 127.0.0.1:1337 at Object.exports._errnoException (util.js:1018:11) at exports._exceptionWithHostPort (util.js:1041:20) at Server._listen2 (net.js:1258:14) at listen (net.js:1294:10) at net.js:1404:9 at _combinedTickCallback (internal/process/next_tick.js:83:11) at process._tickCallback (internal/process/next_tick.js:104:9) at Module.runMain (module.js:606:11) at run (bootstrap_node.js:390:7) at startup (bootstrap_node.js:150:9)

I am just a newbie with NodeJS.



via Terry John

No comments:

Post a Comment