1. We create a project directory.
The code copy is as follows:
> md hello-world
2. Enter this directory and define the project configuration file package.json.
For accurate definition, you can use the command:
The code copy is as follows:
D:/tmp/node/hello-world> npm info expression version
npm http GET https://registry.npmjs.org/express
npm http 200 https://registry.npmjs.org/express
3.2.1
Now that the latest version of ExpressJS framework is 3.2.1, the configuration file is:
The code copy is as follows:
{
"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.
The code copy is as follows:
> npm install
Once the npm installation dependency package is completed, the subdirectory of node_modules will appear in the project root directory. The express packages required for project configuration are stored here. If the phase is verified, you can execute the command:
The code copy is as follows:
> npm ls
PS D:/tmp/node/hello-world> npm ls
npm WARN package.json [email protected] No README.md file found!
[email protected] D:/tmp/node/hello-world
│ ├── [email protected]
│ ├── [email protected]
│ └── [email protected]
This command displays the express package and its dependencies.
4. Create an application
Now start creating the application itself. Create a file called app.js or server.js, depending on what you like, choose any one. Refer to express and create a new application using express():
The code copy is as follows:
// app.js
var express = require('express');
var app = express();
Next, we can use app.verb() to define the route.
For example, use "GET /" to respond to the "Hello World" string, because res and req are accurate objects provided by Node, so you can call res.pipe() or req.on('data', callback) or others.
The code copy is as follows:
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:
The code copy is 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:
The code copy is as follows:
> node app.js
Access the address with the browser: http://localhost:3000/hello.txt
You can see the output result:
The code copy is as follows:
Hello World