1) 安装express
npm install -g express-generator
2) 新建nodeApp
express nodeApp
3) 安装依赖
cd nodeApp && npm install
4) 项目列表
package.json // 依赖 命令行
package-lock.json
app.js // 入口文件
views
routes
public // 静态文件
css
img
js
node_modules // 依赖
bin // listen:3000
www // npm start 启动时调用的JS脚本文件
5) 启动
SET DEBUG=nodeApp:* & npm start
6) 热更新
因为在使用的过程中 更改了routes 中 index.js中的内容 发现没有用 所以觉得可能需要热更新 便去查询了一下 整理了代码
var express = require('express');
var app = express();
var fs = require("fs");
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
// 为了路由能够热更新
app.use('/', function(req,res,next){
indexRouter(req,res,next)
});
// 热更新
function cleanCache ( modulePath ) {
var module = require.cache[modulePath];
if (!module) {
return;
}
// remove refrece in module.parent
if(module.parent){
module.parent.children.splice(module.parent.children.indexOf(module), 1);
}
require.cache[modulePath] = null; // reset
}
var watchFile = function ( filepath ){
var fullpath = require.resolve(filepath);
fs.watch(fullpath,function( event,filename ){
if (event === "change") {
cleanCache(fullpath);
try {
var routes = require(filepath);
console.log("reload module",filename);
} catch (ex) {
console.error('module update failed');
}
}
})
}
// 需要进行热更新的文件
var WatchFileAll = ["./routes/index"];
for (var i=0;i<g_WatchFiles.length;i++) {
watchFile(WatchFileAll [i]);
}
setInterval(function() {
indexRouter = require('./routes/index');
}, 1000);
也可以通过安装nodemon来进行热更新
npm install nodemon -g
// 更改package.json:
"scripts": {
"start": "set DEBUG=myapp & nodemon ./bin/www"
}
// 之后每次更新文件 服务器都会更新并重新启动
7) 测试路由
在app.js同级的位置新建一个JS文件 about.js
在routes的index.js文件下加入以下代码
router.get('/about', function(req, res, next) {
res.send('hello node about');
});
访问http://localhost:3000/about 则可以看到 hello node about
8) 路由方法
// get post put delete all
// GET method route
app.get('/', function (req, res) {
res.send('GET request to the homepage');
});
// POST method route
app.post('/', function (req, res) {
res.send('POST request to the homepage');
});
10) 连接后台 连接mySQL 或者 mongDB
// 安装mySQL并连接数据库
npm install mysql -g