NodeJs书写一个Web服务器
// 引用使用模块
const http = require("http"),
fs = require("fs"),
path = require("path"),
url = require("url");
// 获取当前目录
var root = path.resolve();
// 创建服务器
var sever = http.createServer(function(request,response){
var pathname = url.parse(request.url).pathname;
var filepath = path.join(root,pathname);
// 获取文件状态
fs.stat(filepath,function(err,stats){
if(err){
// 发送404响应
response.writeHead(404);
response.end("404 Not Found.");
}else{
// 发送200响应
response.writeHead(200);
// response是一个writeStream对象,fs读取html后,可以用pipe方法直接写入
fs.createReadStream(filepath).pipe(response);
}
});
});
sever.listen(8080,()=>{
console.log('Sever is running at http://127.0.0.1:8080/')
});
本文来自博客园,作者:码农阿亮,转载请注明原文链接:https://www.cnblogs.com/wml-it/p/16994726.html
技术的发展日新月异,随着时间推移,无法保证本博客所有内容的正确性。如有误导,请大家见谅,欢迎评论区指正!
开源库地址,欢迎点亮:
GitHub:https://github.com/ITMingliang
Gitee: https://gitee.com/mingliang_it
GitLab: https://gitlab.com/ITMingliang
建群声明: 本着技术在于分享,方便大家交流学习的初心,特此建立【编程内功修炼交流群】,为大家答疑解惑。热烈欢迎各位爱交流学习的程序员进群,也希望进群的大佬能不吝分享自己遇到的技术问题和学习心得!进群方式:扫码关注公众号,后台回复【进群】。
