// 使用 require 指令来载入 http 模块
const http = require('http')
// 使用 fs 模块,来读取文件
const fs = require('fs')
// 创建服务器
const server = http.createServer((request, response) => {
// 监听到有客户端请求时,会自动调用该回调函数处理请求并返回响应
const {url, method} = request // 解构赋值
// const url = request.url
// const method = request.method
console.log('url:', url, ', method:', method)
// 服务端路由的处理
let html = 'Hello NodeJS'
switch(url) {
case '/index.html':
html = fs.readFileSync('./www/index.html')
break
case '/login.html':
html = '<h1>user login</h1>'
break
case '/login.do':
// TODO: 连接数据库,比较用户名密码数据,返回响应
}
// 返回响应
response.end(html)
})
// 监听端口,等待客户端连接
// 端口号范围 0 - 65535,前 1024 个端口通常预留
// http 默认 80 端口、https 默认 443 端口
// chrome 浏览器中测试时,不要监听 6666 端口
server.listen(3000, () => console.log('Server running at http://localhost:3000'))
NodeJS
菜鸟教程
官网
简单的说 Node.js 就是运行在服务端的 JavaScript。
Node.js 是一个基于Chrome JavaScript 运行时建立的一个平台。
npm
node package manager(node包资源管理器)
$ npm install <package-name> -g --save-dev
$ npm i <package-name>
package.json
项目配置文件
生成 package.json 文件:
$ npm init -y
模块化
模块化规范:
AMD(异步模块定义) - require.js
CMD - sea.js
CommonJS - NodeJS(一个文件就是一个模块,require() 引入依赖模块, module.exports 定义导出模块)
ES6 - import / export
nodemon
这是一个能够监视文件变化,在文件变化后自动重启 node 应用的工具
$ npm i nodemon -g
安装成功后,在命令行中就可以使用 nodemon 代替 node 命令执行任务
Express
中文网
基于 Node.js 平台,快速、开放、极简的 Web 开发框架
使用
安装
$ npm i express
定义 app.js
// 引入 express 模块
const express = require('express')
// 创建 Express 应用实例
const app = express()
// 静态资源托管
app.use(express.static('public'))
// 监听端口,等待连接
app.listen(3333, () => console.log('Server running at http://localhost:3333'))
启动服务器
$ nodemon app.js