1. We create the project directory.
> md hello-world
2. Enter this directory and define the project configuration file package.json.
For precise definition, you can use the command:
D:tmpnodehello-world> npm info express version
npm http GET https://registry.npmjs.org/express
npm http 200 https://registry.npmjs.org/express
3.2.1
Now we know that the latest version of ExpressJS framework is 3.2.1, then the configuration file is:
{
"name": "hello-world",
"description": "hello world test app",
"version": "0.0.1",
"private": true,
"dependencies": {
"express": "3.2.1"
}
}
3. Use npm to install the packages that the project depends on.
> npm install
Once npm installation of dependent packages is completed, a subdirectory of node_modules will appear in the project root directory. The express packages required for project configuration are stored here. If verified, you can execute the command:
> npm ls
PS D:tmpnodehello-world> npm ls
npm WARN package.json hello-world@0.0.1 No README.md file found!
hello-world@0.0.1 D:tmpnodehello-world
└─┬ express@3.2.1
├── buffer-crc32@0.2.1
├── commander@0.6.1
├─┬ connect@2.7.7
│ ├── bytes@0.2.0
│ ├── formidable@1.0.13
│ └── pause@0.0.1
├── cookie@0.0.5
├── cookie-signature@1.0.1
├── debug@0.7.2
├── fresh@0.1.0
├── methods@0.0.1
├── mkdirp@0.3.4
├── qs@0.6.1
├── range-parser@0.0.4
└─┬ send@0.1.0
└── mime@1.2.6
This command shows express packages and their dependencies.
4. Create an application
Now start creating the application itself. Create a file called app.js or server.js, whichever you prefer. Reference express and create a new application using express():
// app.js
var express = require('express');
var app = express();
Next, we can use app.verb() to define routes.
For example, use "GET /" to respond to the "Hello World" string. Because res and req are accurate objects provided by Node, you can call res.pipe() or req.on('data', callback) or others.
app.get('/hello.txt', function(req, res){
var body = 'Hello World';
res.setHeader('Content-Type', 'text/plain');
res.setHeader('Content-Length', body.length);
Res.end(body);
});
The ExpressJS framework provides higher-level methods, such as res.send(), which can save things like adding Content-Length. As follows:
app.get('/hello.txt', function(req, res){
res.send('Hello World');
});
Now you can bind and listen to the port. Call the app.listen() method and receive the same parameters, such as:
5. Run the program
Now run the program and execute the command:
> node app.js
Use a browser to access the address: http://localhost:3000/hello.txt
You can see the output:
Hello World