小工具
在使用npm start 的时候,需要不断的修改代码,但是命令行不会实时的更新,nodemon实时的更新命令行
npm install --save-dev nodemon
- 替换node为nodemon
- 之前的 "start": "node index.js"
- 改成 "start": "nodemon index.js"
npm 6.4之后添加了--inspect来调试浏览器
- "start": "nodemon --inspect index.js"
1.node.js的核心模块
利用node.js 的http模块和fs模块写一个读取网页的静态服务器
主要运用http模块的createServer和listen, fs模块的readfile
http.createServer(): 创建服务器。接受一个函数,函数的二个参数分别是请求和相应(request require)
http.listen():监听端口。接受一个PORT,一个回调函数
fs.readfile(): 异步读取数据,一个是文件路径,相对于process.cwd()的路径(current word directory),而不是相对于当前脚本所在的路径。一个设置编码形式。还有一个是回调函数。
const http = require('http');
http.createServer((request,response)=>{....
}).listen(PORT,()=>{console.log(`server listening on port ${PORT}`)})
const fs = require('fs');
fs.readfile('./src/index.html','utf8',()=>{
console.log(.....);
})
2. 开启项目
为了方便后期调试,我们先在npm script 中添加
"start": "node index.js"

// index.js文件内容
/**
* 尝试开启静态服务器
*/
const http = require('http');
const PORT = 9000;
http.createServer((request,response)=>{
response.end('hcc')
}).listen(PORT,()=>{
console.log(`server listening on port ${PORT}`)
});
-
在命令行中输入npm start
npm strat.png
- 在浏览器中输入localhost:9000
浏览器中显示hcc字符串
3.学过模块化,主要功能和服务器分离
创建一个app文件夹写主要的功能

// app文件夹下面的 index.js
class Server{
constructor(){
}
initServer(request,response){
response.end('This is a Server')
}
// 如果想设置中文,请在响应头中添加编码方式
// response.write('<head><meta charset="utf-8"/></head>')
}
module.exports = {
Server
}
// 根目录下面的index.js
const http = require('http');
const PORT = 9000;
const Server = require('./app').Server;
const server = new Server();
http.createServer(server.initServer).listen(PORT,()=>{
console.log(`server listening on port ${PORT}`)
});
-
在命令行中输入npm start
npm strat.png
- 在浏览器中输入localhost:9000
浏览器中显示This is a Server字符串
4. 读取文件
新建一个src存放项目的源文件

// src下面的index.html
存放我们想要拷贝的源代码
// app文件夹下面的 index.js
const fs = require('fs');
class Server{
constructor(){
}
initServer(request,response){
//这里的文件路径是按照当前工作目录执行
fs.readFile('./src/index.html','utf8',(error,data)=>{
response.end(data);
})
}
}
module.exports = {
Server
}
// 根目录下面的 index.js
const http = require('http');
const PORT = 9000;
const Server = require('./app').Server;
const server = new Server();
http.createServer(server.initServer).listen(PORT,()=>{
console.log(`server listening on port ${PORT}`)
});
5.修改成高级函数
如果我们想在主要的功能函数中还继续做点事情,就可以利用一个函数返回一个函数
// app文件夹下面的 index.js
const fs = require('fs');
class Server{
constructor(){
}
initServer(){
// 做相应的事情
return (request,response)=>{
fs.readFile('./src/index.html','utf8',(error,data)=>{
response.end(data);
})
}
}
}
module.exports = {
Server
}
// 跟目录下面的index.js
const http = require('http');
const PORT = 9000;
const Server = require('./app').Server;
const server = new Server();
// 修改成执行函数
http.createServer(server.initServer()).listen(PORT,()=>{
console.log(`server listening on port ${PORT}`)
});
网友评论