The concept of a java script server is in my opinion revolutionary because of the fact that frontend technology also can be separated from the backend as a specialism. But what good is the one without the other. Creating a presentation is no good without data. But what good is data if we cannot present it. So in this matter I would show you that it is possible to combine the best of both worlds.
The solution:
In my previous post I described how to install a nodejs server and create an hello world application.
Because connecting to a rest service is a bit more complex we need to do some actions before we can start:
create an folder for example rest-api
cd rest-api
We need the superagent library:
npm install superagent@0.17.0 --save-dev
After this we can start building up the server:
// initializing the http package.
var http = require("http"),
//making the port available through a parameter
port = process.argv[2] || 8888;
// initializing the superagent package
var superagent = require('superagent');
// creating the http server
http.createServer(function(request, response) {
//retrieving the rest url throught the superagent package
superagent.get('http://localhost:8080/hello')
.end(function(e, res){
//writing the res.text response from the rest server to the response which is the browser client response.
response.write(res.text, "binary");
response.end();
})
//make the server listen to the port that is declared in my case 8090 or the standard port 8888
}).listen(parseInt(port, 10));
//just a friendly console message.
console.log("Static file server running at\n => http://localhost:" + port + "/\nCTRL + C to shutdown");
Conclusion:
The world of javascript is not that different from the world of Java these days. There is this virtual machine, it is getting Object Oriented in a kind of way and you have to know your way in the library wilderness. This makes the gap between the two worlds smaller. There are still differences between the way of working between these kind of frontend technologies and Java as allways the devil is in the details.
Have fun!