1. http 模块
一个简单的服务器
const http = reqiue('http');
const server = http.createServer((req, res) => {
console.log(req.url); // 请求 url
console.log(req.method); //请求方法
console.log(req.headers); //请求头部
if(req.url === '/'){
// 设置响应的状态码和头部
res.writeHead(200, {'Content-Type': 'text/plain; charset=utf-8'});
// 单独设置状态码
res.statusCode = 200;
// 单独设置响应头部
res.setHeader('Content-Type', 'text/plain; charset=utf-8');
// Set-Cookie
res.setHeader('Set-Cookie', 'name=song; secure');
// 设置响应体
res.write("Hello World");
res.write("!!!")
// 发送响应报文
res.end();
}
})
server.listen(3000, () => {
console.log("服务器跑在 3000 端口");
})设置静态目录
const http = reqiue('http');
const server = http.createServer((req, res) => {
console.log(req.url); // 请求 url
console.log(req.method); //请求方法
console.log(req.headers); //请求头部
if(req.url === '/'){
// 设置响应的状态码和头部
res.writeHead(200, {'Content-Type': 'text/plain; charset=utf-8'});
// 单独设置状态码
res.statusCode = 200;
// 单独设置响应头部
res.setHeader('Content-Type', 'text/plain; charset=utf-8');
// Set-Cookie
res.setHeader('Set-Cookie', 'name=song; secure');
// 设置响应体
res.write("Hello World");
res.write("!!!")
// 发送响应报文
res.end();
} else {
let filePath = path.join(__dirname, 'static', url.pathname);
try{
let file = await fs.readFileAsync(filePath);
res.statusCode = 200;
res.end(file);
} catch(error){
res.statusCode = 404;
res.end("404 Not Found");
}
}
// 或者
else {
let fileName = url.pathname;
let type;
switch(fileName.substr(fileName.lastIndexOf('.') + 1)){
case 'css':
type = 'text/css; charset=utf-8';
break;
case 'js':
type = 'text/javascript; charset=utf-8';
break;
default:
type = 'application/octet-stream';
break;
}
try{
let file = await fs.readFileAsync(`./static${url.pathname}`)
res.writeHeader('Content-Type', 'type');
res.end(file);
} catch{
res.writeHead(400, {'Content-Type': 'text/plain; charset=utf-8'});
res.end("404错误")
}
}
})
server.listen(3000, () => {
console.log("服务器跑在 3000 端口");
}) 处理 post 请求(文件上传)
// 前端部分
let type = typeof data;
let header;
if(type === 'string'){
header = 'application/x-www-form-urlencoded';
} else if(data instanceof File || data instanceof FormData){
header = 'multipart/form-data; boundary=---xxxxxxxxxx';
} else {
header = 'application/json';
data = JSON.stringify(data);
}
xhr.setRequestHeader('Content-Type', header);
xhr.send(data);
// 后端
const http = require('http');
const fs = require('fs');
const server = http.createServer((req, res) => {
if(req.url === '/upload'){
let segment = [];
req.on('data', chunk => {
// chunk 为 Buffer 对象
// 字符串 aaa=bbb 对应的 Buffer 对象如下
// <Buffer 61 61 61 3d 62 62 62>
segment.push(chunk);
})
req.on('end', () => {
// 文件上传代码
segment = Buffer.concat(segment);
// 下方代码获取 Buffer 转成的字符串
// segment = Buffer.concat(segment).toString()
fs.writeFile('fileName', segment, err => {
res.writeHead(200, {'Content-Type': 'text/plain; charset=utf-8'});
res.write('文件上传成功!');
res.end();
})
})
}
});
server.listen(3000, () => {
console.log('服务器跑在 3000 端口');
}) fs 模块
const fs = require('fs');
// readFile
fs.readFile('./image.png', (err, buffer) => {
if(err) throw err;
});
// writeFile
fs.writeFile('index.txt', 'hello world', 'utf8');
// 写入 buffer
fs.writeFile('image.png', buffer);
const reader = fs.createReadStream(data.path);
const stream = fs.createWriteStream(`./image/${Math.floor(Math.random() * 1000)}.jpg`);
reader.pipe(stream); path 模块
const path = require('path');
__dirname: 返回当前文件所在的绝对路径
path.resolve: 将一个路径解析成绝对路径
const path1 = path.resolve('static');
console.log(path1); // 输出绝对路径
// path.join: 用特定平台的分割符号(Linux 为 /,Windows 为 \)对路径进行拼接
const path1 = path.join(__dirname, 'a');
const path2 = path.join(__dirname, 'a/b');
console.log(path1);
console.log(path2); process 模块
const process = require('process');
process.cwd();
// 获取执行脚本时所在的目录
process.argv;
// 获取执行脚本时命令行输入的参数
// 标准输出流
process.stdout.write('Hello World');
// 标准输入流
process.stdin.on('data', chunk => {
process.stdout.write('Hello' + chunk);
process.exit;
}) child_process 模块
node 中的 child_process 提供了创建子进程的方式。一共有四种,分别是 spawn, execFile, exec, fork。
其中 fork 是用来创建 node 程序的子进程,前三个用来创建 shell 程序的子进程。
spawn, execFile 和 exec 的区别:
首先,spawn 是基于流的形式,而后两者是基于回调的形式。
spawn 和 execFile 的调用方式相同,与 exec 的调用方式不同。
另外使用 exec 执行一些危险的脚本(如 rm -rf)是会直接执行的;而 execFile 碰到一些危险的操作会爆出异常。因此 execFile 的安全性更高。
event 模块
var EventEmitter = require('events').EventEmitter;
var emitter = new EventEmitter();
emitter.on('ev', function(){});
emitter.emit('ev');

京公网安备 11010502036488号