Wednesday, January 1, 2014

Introduction to Node.js

What is Node.js?

Node.js is a JavaScript run-time environment built on top of Chrome V8 JavaScript engine for building scalable network applications. It's written in C, C++ and JavaScript. Node.js uses event driven, non-blocking I/O model which is lightweight and efficient. Node.js has a package manager called npm.

Getting Started

First install Node.js. Then create a new folder and run npm init in Node.js command prompt. You'll be guided through a set of steps to create the folder structure. After this you'll have package.json file created for you.



In root, create index.js file and add console.log('Hello World'); if you run the node app now, you'll see Hello World in command prompt.



Create a index.html file with some content and add the following code to index.js file


Type http://localhost:8000/ in the browser and your Node server is up and running on port 8000.

Creating an REST API with Node and SQLite

Let's see how to create a simple REST API with Node.js. For database connectivity i'll use SQLite.

First install following node packages

  • SQLite3 for storage
  • Express.js web server to manage endpoints, requests and responses
  • md5 to hash passwords of users

Handling CORS(Cross-Origin Resource Sharing)

Due to CORS restriction, you cannot access the resources even in localhost from another application. We use cors package in npm and use it as an application level middleware to handle CORS. 

Here's code for server.js


This is the code for database.js where we define and initialize the database


Here in database file ':memory:' will initialize the database in memory.


When to use Node.js?


Node.js in production

1 comment:

Powered by Blogger.


Software Architect at Surge Global/ Certified Scrum Master

Experienced in Product Design, Software Engineering, Team management and Practicing Agile methodologies.

Search This Blog

Facebook