Node.js是基于Chrome V8引擎的Javascript运行环境
Node.js使用了一个事件驱动、非堵塞式I/O模型,使其轻量又高效
Node.js的包管理器npm,是全球最大的开源库生态系统
准备:node环境。
1、shell命令: mkdir NodeTest 新建NodeTest文件夹
2、cd NodeTest 进入文件夹
3、touch app.js 新建app.js文件
4、编写app.js文件,先开启服务
const http = require('http')
const myServer = http.createServer(function(req, res) {
})
myServer.listen(3000, function() {
console.log('开启端口为3000的服务')
})
5、shell: node app.js 执行脚本
6、mkdir view 新建view文件夹
7、touch index.html 常规操作
8、app.js返回index的内容
const http = require('http')
const path = require('path')
const fs = require('fs')
const myServer = http.createServer(function(req, res) {
const url = path.join('view', 'index.html')
const content = fs.readFileSync(url)
res.write(content)
res.end() //服务器响应结束
})
myServer.listen(3000, function() {
console.log('开启端口为3000的服务')
})
访问localhost:3000 即可看到页面
9、根据路由返回页面 在view下面新建info.html
const http = require('http')
const path = require('path')
const fs = require('fs')
const myServer = http.createServer(function(req, res) {
console.log(req.url)
const url = req.url === '/' ? 'index.html' : req.url
let fileUrl = path.join('view', url)
fileUrl = fs.existsSync(fileUrl) ? fileUrl:path.join('view', 'err', '404err.html')
const content = fs.readFileSync(fileUrl)
res.write(content)
res.end() //服务器响应结束
})
myServer.listen(3000, function() {
console.log('开启端口为3000的服务')
})
细品