参考资料:《node.js开发指南》
1.安装Node.js,从官网下载,很容易,里面自带npm
2.Hello World。打开你常用的文本编辑器,在其中输入:
console.log('Hello World');
将文件保存为 helloworld.js ,打开终端,进入 helloworld.js 所在的目录,执行以下命令:
node helloworld.js
如果一切正常,你将会在终端中看到输出 Hello World。
3.建立HTTP服务器。建立一个名为 app.js 的文件,内容
为:
//app.js
var http = require('http');
http.createServer( function (req, res) {
res.writeHead( 200 , {'Content-Type': 'text/html'});
res.write('<h1>Node.js</h1>');
res.end('<p>Hello World</p>');
}).listen(3000);
console.log("HTTP server is listening at port 3000.");
接下来运行 node app.js 命令,打开浏览器访问 http://127.0.0.1:3000
4.npm 提供了大量的第三方模块,其中不乏许多 Web 框架,我们没有必要重复发明轮子,
因而选择使用 Express 作为开发框架,因为它是目前最稳定、使用最广泛,而且 Node.js 官
方推荐的唯一一个 Web 开发框架。
安装express,见文章http://blog.csdn.net/zcgsdu/article/details/38959361
使用ejs模板引擎建立项目结构,见文章http://blog.csdn.net/zcgsdu/article/details/38959459
启动服务器,在项目目录下,npm start,浏览器访问http://127.0.0.1:3000/
5.要关闭服务器的话,在终端中按 Ctrl + C 。注意,如果你对代码做了修改,要想看到修
改后的效果必须重启服务器,也就是说你需要关闭服务器并再次运行才会有效果。
6.项目目录结构:
(1)app.js
app.js 是工程的入口(这里需要注意 express 4.x 无法以 node app.js 为启动方式,而是用指令 npm start 作为启动)
(2)routes/index.js
routes/index.js 是路由文件,相当于控制器,用于组织展示的内容
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res) {
res.render('index', { title: 'Express' });
});
module.exports = router;
其中这句话,
res.render('index', { title: 'Express' });
index调用的是views/index.ejs
(3)views/index.ejs
index.ejs 是模板文件,即 routes/index.js 中调用的模板,内容是:
<!DOCTYPE html>
<html>
<head>
<title><%= title %></title>
<link rel='stylesheet' href='/stylesheets/style.css' />
</head>
<body>
<h1><%= title %></h1>
<p>Welcome to <%= title %></p>
</body>
</html>
它的基础是 HTML 语言,其中包含了形如 <%= title %> 的标签,功能是显示引用的变
量,即 res.render 函数第二个参数传入的对象的属性。
(4)public
包含images,javascripts,stylesheets