利用node启动简单的静态http服务
http模块创建的是http服务
net模块创建的是tcp服务
- 简单的
const http = require('http');
const fs = require('fs');
const path = require('path');
//静态资源的路径
const staticUrl = __dirname;
const server = http.createServer(function(req,res){
//req,res均为对象,req是http.IncomingMessage的一个实例,res是http.ServerResponse的一个实例
const url = req.url;
//浏览器输入localhost:9000/index.html, 那url == '/index.html'
//console.log(url);
const file = staticUrl + url,
type = path.extname(url); //path.extname 返回路径中文件的扩展名
//console.log(type)
type = type ? type.split('.')[1] : 'unknown';
fs.readFile(file , function(err,data){
if(err){
console.log('访问'+staticUrl+req.url+'出错');
res.writeHeader(404,{
'content-type' : 'text/html;charset="utf-8"'
});
res.write('<h1>404错误</h1><p>你要找的页面不存在</p>');
}else{
res.write(data); //将index.html显示在浏览器(客服端)
}
res.end();
});
}).listen(9097,'127.0.0.1');
console.log('服务器开启成功\n\n访问路径为 http://127.0.0.1:9097/index.html\n');
node 开发调试工具
- supervisor
监听并自动重启服务
#安装
npm install -g supervisor
#使用
supervisor 1.js
- iron-node
简单的调试工具
#安装
npm install iron-node -g
#使用
iron-node 1.js
- nodemon
监听并自动重启服务
#安装
npm install nodemon -g
#使用
nodemon 1.js
node 常用
执行bash命令
const exec = require('child_process').exec;
// 例如ls命令
let ls = exec('ls -al',{cwd:'/Users/mzh'},(err,stdout,stderr)=>{
console.log(`stdout:${stdout}`);
console.log(`stderr:${stderr}`);
if(err !== null){
console.log(`exec error: ${err}`);
}
});
ls.on('exit',(code)=>{
console.log(`child exited with code ${code}`);
});
等同于 bash
ls -al
执行特定的程序
const execFile = require('child_process').execFile;
let runFile = execFile('index.js');
runFile.stdout.on('data',data=>{
console.log(data);
});
let runNode = execFile('node',['--version']);
let runBash = execFile('/bin/ls',['-al','/']);
runNode.stdout.on('data',data=>{
console.log(data);
});
runBash.stdout.on('data',data=>{
console.log(data);
});
创建一个子进程来执行特定命令
const spawn = require('child_process').spawn;
const ps = spawn('ps',['aux']);
const grep = spawn('grep',['zsh']);
ps.stdout.on('data',data=>{
grep.stdin.write(data);
});
ps.on('close',code=>{
if(code !== 0){
console.log(`ps process exited with code ${code}`);
}
grep.stdin.end();
});
grep.stdout.on('data',data=>{
console.log(data);
});
等同于bash
ps aux | grep zsh
开子进程运行
const fork = require('child_process').fork;
let child = fork('./child.js');
child.send('main process');
child.on('message',msg=>{
console.log(`parent get message: ${msg}`);
});
child.js
console.log('child process running...');
process.on('message',msg=>{
console.log(`child get message: ${msg}`);
});
setTimeout(()=>{
process.send('child send message');
},1000);
让子进程的信息和父进程共享(父进程可以显示子进程信息)
const execSync = require('child_process').execSync;
execSync('rm -rf ./dist', {
// stdio 设置父子进程共享的通道
// 等同于[process.stdin, process.stdout, process.stderr];
stdio: [0, 1, 2]
});