1、Demo.js
创建Server
let http = require('http');
let url = require("url");
let util = require("util")
let fs = require("fs"); //文件读取模块
let server = http.createServer((req,res)=>{
res.statusCode = 200;
res.setHeader("Content-Type","text/plain;charset=utf-8");
console.log("url:"+ req.url); //demo.html?a=123
console.log("parse:"+url.parse(req.url)); //[object]
console.log("inspect:"+util.inspect(url.parse(req.url))) //key value的形式的字符串 方便开发和调试
})
res.end();
}).listen(3000,"127.0.0.1",()=>{
console.log("服务器已经运行,请输入浏览,输入http://127.0.0.1:3000 来访问")
})
启动服务 node Demo.js
2、服务读取文件
let http = require('http');
let url = require("url");
let util = require("util")
let fs = require("fs"); //文件读取模块
let server = http.createServer((req,res)=>{
var pathname = url.parse(req.url).pathname;
fs.readFile(pathname.substring(1),(err,data) = >{
if(err){
res.writeHead(404,{
'Content-Type':'text/html'
})
}else{
res.writeHead(200,{
'Content-Type':'text/html'
})
res.write(data.toString()); //写入的数据
}
res.end();
})
}).listen(3000,"127.0.0.1",()=>{
console.log("服务器已经运行,请输入浏览,输入http://127.0.0.1:3000 来访问")
})
启动服务 node Demo.js