There can be console-based and web-based node.js applications.
Node.js console-based Example
File: console_example1.js
Open Node.js command prompt and run the following code:
Here, console.log() function displays message on console.
Node.js web-based Example
A node.js web application contains the following three parts:
- Import required modules: The "require" directive is used to load a Node.js module.
- Create server: You have to establish a server which will listen to client's request similar to Apache HTTP Server.
- Read request and return response: Server created in the second step will read HTTP request made by client which can be a browser or console and return the response.
How to create node.js web applications
Follow these steps:
- Import required module: The first step is to use ?require? directive to load http module and store returned HTTP instance into http variable. For example:
- Create server: In the second step, you have to use created http instance and call http.createServer() method to create server instance and then bind it at port 8081 using listen method associated with server instance. Pass it a function with request and response parameters and write the sample implementation to return "Hello World". For example:
- Combine step1 and step2 together in a file named "main.js".
File: main.js
How to start your server:
Go to start menu and click on the Node.js command prompt.
Now command prompt is open:
Set path: Here we have save "main.js" file on the desktop.
So type cd desktop on the command prompt. After that execute the main.js to start the server as follows:
Now server is started.
Make a request to Node.js server:
Open http://127.0.0.1:8081/ in any browser. You will see the following result.
Now, if you make any changes in the "main.js" file, you need to again run the "node main.js" command.
0 comments:
Post a Comment
Note: only a member of this blog may post a comment.