User Tools

Site Tools



Python Tutorials

WebGL Tutorials

Node.js Tutorials

Node.js in WebStorm

Martin Christen

View Martin Christen's profile on LinkedIn


Timeline of @MartinChristen

MartinChristen avatar

RT @TFConsult: Celebrating 100th birthday of #physicist #RichardFeynman: The marvellous #Feynman lectures on #physics:
About 1 week, 4 days ago by: Martin Christen (@MartinChristen)

MartinChristen avatar

RT @sergerey: Had a fantastic time giving our workshop on Spatial Data Science with PyData at @GeoPythonConf with @levijohnwolf. Looking f…
About 1 week, 5 days ago by: Martin Christen (@MartinChristen)

MartinChristen avatar

RT @fridex: Everything has an end even such an excellent conference #GeoPythonConf in Basel. Thanks to organizers for such an outstanding c…
About 1 week, 5 days ago by: Martin Christen (@MartinChristen)

Node.js Tutorials - Part 0

Node.js Tutorial 2

Returning Dynamic JSON

In this tutorial we create a more dynamic JSON response and also listen to other events. The goal of this tutorial is running a Web Application which returns the following JSON response:

  "greeting": "Hello World",
  "date": "2013-06-30T13:56:14.794Z",
  "user-agent": "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:21.0) Gecko/20100101 Firefox/21.0"

Where “date” contains the current date and “user-agent” contains the user agent of the request header. In this example we also want to add custom listeners for some http-Server events.

var http = require('http');
var myServer = http.createServer(function (){});

In this first part we create the server as we already did in the last tutorial.

myServer.addListener("connection", function(){
We add a listener which emitted when a new TCP stream is established.

myServer.addListener("request", function(req, res) {
  res.writeHead(200, {'Content-Type': 'application/json'});
  var myObject = {};
  myObject['greeting'] = 'Hello World';
  myObject['date'] = new Date();
  myObject['user-agent'] = req.headers['user-agent'];
  res.end(JSON.stringify(myObject, undefined, 2));

The “request” event is emitted when there is a request. Here we set the content type to application/json and create a JSON object containing a greeting, a date, and the user-agent. The JSON object is serialized using the stringify function.

myServer.listen(1234, '');

The server starts to listen at port 1234.

node/tutorial02.txt · Last modified: 2013/09/16 22:05 by mchristen