Posts Tagged ‘tutorial’

Building a simple joke site with Nodejs – Part 2 – Reading JSON from files

Thursday, June 11th, 2015 by Phillip Napieralski

Last time we set-up NodeJS and built a simple “Hello world” app. This time, let’s have it serve up something more interesting. As a first step to building our joke website, let’s read two jokes from a file and print them out to the screen.

The “backend database” format

JSON is arguably the most widely used format to store objects with javascript. Backend databases like the document based MongoDB works seamlessly with the format. So, let’s use it!

Dump this into a file called jokesDB.json

[
	{
		'category': 'chucknorris',
		'content': 'When chuck norris does a push-up, he's actually pushing the world down.'
	},
	{
		'category': 'yomomma',
		'content': 'Yo momma house so dirty, she has to wipe her feet before she goes outside.'
	}
]

Place this file in the same directory you plan to keep your code. It will act as a temporary database from where we can retrieve our jokes.

NOTE: You probably wouldn’t want to use a flat file for a production website. Especially if you want to be able to add and remove jokes quickly from your “database.” Later on we’ll add a real database solution for which to store our data.

Our “database” module

To facilitate a clean separation later on, it makes sense to start, even now, putting our backend logic all in a separate module. You’ll thank me later when our module to interface with the database has 100s of lines of code.

Create a new file in the same directory as your jokesDB.json file and call it “database.js”. Copy this code to it:

var fs = require('fs');

module.exports =
{
	getJokesFromDB: function()
	{
		return fs.readFileSync('jokesDB.json').toString();
	}
}

That’s it! Now we just need to modify our server.js code.

The new server code

If you still have your code from the previous tutorial (part 1), it’ll be easy to modify the code to load the database module and show the jokes. Here’s what your new server.js file should look like:

// node modules
var http = require('http');

// our created modules
var db = require('./database');

// Handle a general user request
function handleRequest(request, response) {
	response.writeHead(200, {'Content-Type': 'text/html'});
	var jokesJson = db.getJokesFromDB();
	response.end(jokesJson);
}

http.createServer(handleRequest).listen(80, "127.0.0.1");

console.log('Server running at http://127.0.0.1:80');

Show me the jokes!

Now the magical part – let’s see what we’ve done so far. Open up a terminal/command prompt, navigate to your directory (eg; ‘cd D:\nodescripts\) and type the following:

node server.js

Conclusion

I showed you how to use the fs module to load in a file and output that data to a file! You’ll now see the simple file outputted to the browser when you navigate to http://localhost or http://127.0.0.1 (they are the same). Next time, we’ll bring expressjs in the mix to give us the ability to easily add other pages.