Part2 : LET'S DO "HELLO, WORLD!"
Fire up your favorite text editor or IDE. I like Sublime Text a lot. Point it at your nodetest1 directory and open app.js. This is kind of the heart of your, well, app. Not a big surprise there. Here's a breakdown of what you're going to see:
选择你最喜欢的编辑器或集成开发环境. 我比较喜欢 Sublime Text. 点击你的nodetest1目录下, 打开app.js文件. 这是你的应用的"心脏".
var express = require('express'); var routes = require('./routes'); var user = require('./routes/user'); var http = require('http'); var path = require('path');1 第一部分换行前的内部如上, This creates a bunch of basic JavaScript variables and ties them to certain packages, dependencies, node functionality, and routes. 这里创建了一连串的JS变量, 连接一些特定的包, 依赖, node和路由.
var app = express();
2 This one's important. It instantiates Express and assigns our app variable to it. The next section uses this variable to configure a bunch of Express stuff. 这个非常重要, 实例化一个Express对象,并赋值给变量app. 后面的部分可以应用该变量配置一些Express内容.
app.get('/', routes.index); app.get('/users', user.list);3 路由部分
http.createServer(app).listen(app.get('port'), function(){ console.log('Express server listening on port ' + app.get('port')); });4 这部分创建了我们的http服务并launch它.
A: 第1步: APP.JS的app.get()路由中加入
app.get('/helloworld', routes.helloworld);
B: 第2步: 打开routes/INDEX.JS , 在文件的最后加入如下代码:
exports.helloworld = function(req, res){ res.render('helloworld', { title: 'Hello, World!' }); };C: 第3步: Views下创建helloworld.ejs文件, 文件中输入如下内容
<html> <head> <title></title> </head> <body> <p> <%= title %> </p> </body> </html>Save the file, go to your command prompt, ctrl-c to kill app.js if it's already running, and then type:
D: 第4步: http://localhost:3000/helloworld and enjoy the completely asinine text that gets displayed: