Seagull on Post

Development Speed

One of the things I look at when I’m developing something is how fast I can get the project launched. This is one of the things, more than any other, that calls me to NodeJS. It is very simple and easy to get something running. In fact, I’m going to take you through a quick process on serving data from a JSON file stored locally within the folder structure. Below you’ll find JSON for Movie Objects.

{
  "movie1" :
  {
    "name" : "Batman",
    "Release" : "1989",
    "id" : 1
  },
  "movie2" :
  {
    "name" : "Hercules",
    "Release" : "2014",
    "id" : 2
  },
  "movie3" :
  {
    "name" : "Tron",
    "Release" : "1982",
    "id" : 3
  },
  "movie4" :
  {
    "name" : "Repo Men",
    "Release" : "2010",
    "id" : 4
  }
}

Save that in a folder named “MovieAPI” as “movies.json”.

In the same folder, create a text file named App.js. Inside App.js, we’re going to write the following code:

var express = require('express');
var app = express();
var fs = require('fs');

app.get('/listMovies', function(req, res) {
  fs.readFile(__dirname + '/' + 'movies.json', 'utf8', function(err,data){
    console.log(data);
    res.end(data);
  });
})

app.get('/getMovieByID/:id', function(req, res){
  fs.readFile(__dirname + '/'+ 'movies.json', 'utf8', function(err,data){
    movies = JSON.parse(data);
    var movie = movies["movie" + req.params.id]
    console.log(movie);
    res.end(JSON.stringify(movie));
  });
})

var server = app.listen(8081, 'localhost', function() {
  var host = server.address().address
  var port = server.address().port

  console.log("Example App listening at http://%s:%s", host, port)
})

Once you’ve done that, you’ll need to launch a command prompt window. Use CD to change your directory to your MovieAPI, and then type the following:

npm install express

npm install fs

That will install Express and FS so that your project can use them. Then run your project by typing the following:

node app.js

Then go to http://localhost:8081/listMovies in your browser, and you should get a list of movies.

Try http://localhost:8081/getMovieByID/2 – You should get the following string back:

{"name":"Hercules","Release":"2014","id":2}

The speed with which you can set up an API like this on your system is useful to me; it is one of the biggest reasons I enjoy using Node.JS for setting up restful API’s.

spacer

Leave a reply