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

On my way to the 3D city model workshop in Bonn where I‘m presenting our latest @igeoFHNW #AugmentedReality App…
About 5 days, 7 hours ago by: Martin Christen (@MartinChristen)

MartinChristen avatar

Teaching #Python to 11-13-year-old girls was great fun today at the Swiss national future day (#zukunftstag).…
About 1 week, 2 days ago by: Martin Christen (@MartinChristen)

MartinChristen avatar

RT @GeoPythonConf: Interested in joining GeoPython 2019? Register to the mailing list: #python #GeoPython #geospat…
About 2 weeks, 2 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