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.
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.
First install following node packages
Here in database file ':memory:' will initialize the database in memory.
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
http://blog.carbonfive.com/2014/06/02/node-js-in-production/
http://blog.risingstack.com/node-js-is-enterprise-ready/
https://www.paypal-engineering.com/2013/11/22/node-js-at-paypal/
http://chetansurpur.com/blog/2010/10/why-node-js-is-totally-awesome.html
http://blog.mixu.net/2011/02/01/understanding-the-node-js-event-loop/
http://blog.risingstack.com/node-js-is-enterprise-ready/
https://www.paypal-engineering.com/2013/11/22/node-js-at-paypal/
http://chetansurpur.com/blog/2010/10/why-node-js-is-totally-awesome.html
http://blog.mixu.net/2011/02/01/understanding-the-node-js-event-loop/
Thanks for sharing this awesome and very informative blog.
ReplyDeleteNode JS Online training
Node JS training in Hyderabad