做爲程序猿,能夠沒有女友(好像也只能接收找不到的現實),但絕對不能沒有格子衫、護髮素····和對原生的摯愛,今天,我們就來手寫一個簡單的node服務器吧html
話很少說,代碼可得node
let http = require('http');
let fs = require('fs');
let url = require('url');
let queryString = require('querystring');
let server = http.createServer((req,res)=>{
let {pathname,query} = url.parse(req.url,true);
console.log('有訪問',)
//字符串模板
fs.readFile(`./www/${pathname}`,(err,data)=>{
if(err){
res.writeHead(404);
res.write('NOT Found');
res.end();
}else {
console.log(query.a)
res.write(data);
res.end();
}
複製代碼
let server = http.createServer((req,res)=>{
// console.log(1)
let pathName, getQuery , postQuery;
if(req.method=='GET'){
let {pathname, query} = url.parse(req.url,true);
pathName = pathname;
getQuery = query;
}else if(req.method == 'POST'){
let arr = [];
pathName = req.url;
//post請求會分批發送,因此會觸發屢次data事件
req.on('data',buffer=>{
arr.push(buffer);
})
req.on('end',()=>{
arr = Buffer.concat(arr);
console.log(arr.toString('utf-8'))
postQuery = arr.toString();
res.writeHead(200,{'Content-Type':'text/html;charset=utf-8'});
res.write('上傳成功');
res.end();
})
}
// console.log(pathName, getQuery , postQuery);
});
複製代碼
const http=require('http');
const util=require('buffer_util');
const fs=require('fs');
http.createServer((req, res)=>{
let boundary='--'+req.headers['content-type'].split('; ')[1].split('=')[1];
let arr=[];
req.on('data', buffer=>{
arr.push(buffer);
});
req.on('end', ()=>{
let buffer=Buffer.concat(arr);
//1.按照分隔符切分
let res=util.bufferSplit(buffer, boundary);
res.pop();
res.shift();
//2.每個處理一下
res.forEach(buffer=>{
buffer=buffer.slice(2, buffer.length-2);
let n=buffer.indexOf('\r\n\r\n');
let info=buffer.slice(0, n).toString();
let data=buffer.slice(n+4);
if(info.indexOf('\r\n')!=-1){
//文件
let res2=info.split('\r\n')[0].split('; ');
let name=res2[1].split('=')[1];
let filename=res2[2].split('=')[1];
name=name.substring(1, name.length-1);
filename=filename.substring(1, filename.length-1);
fs.writeFile(`upload/${filename}`, data, err=>{
if(err){
console.log(err);
}else{
console.log('上傳成功');
}
});
}else{
//普通訊息
let name=info.split('; ')[1].split('=')[1];
name=name.substring(1, name.length-1);
}
});
});
}).listen(8080);
複製代碼