创建简单的node服务器实例(分享)
话不多说直接上代码:
varhttp=require('http')
//对URL解析为对象
//1.导入模块URl模块
varurl=require('url')
varfs=require('fs')
varpath=require('path')
varmime=require('./mime.js')
varqs=require('querystring')
http.createServer(function(req,res){
varurl1=req.url
varpathname=url.parse(url1).pathname
//打印路径
console.log(pathname)
//取扩展名
varext=path.extname(pathname).slice(1)
varcontentType=mime.types[ext]
fs.exists(__dirname+pathname,function(e){
if(e){
console.log("文件存在")
fs.readFile(__dirname+pathname,function(err,data){
if(!err){
//返回数据
res.writeHead(200,{"Content-Type":contentType+";charset=utf-8","Access-Control-Allow-Origin":"*"})
res.write(data)
res.end()
}else{
console.log("读文件出错")
}
})
}else{
console.log("文件不存在")
}
})
//设置端口
}).listen(9796)
好啦!大概就是这个样子!
有不懂得留言问我哦!
以上这篇创建简单的node服务器实例(分享)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。
热门推荐
10 新人红包祝福语简短精辟
11 幼师给毕业祝福语简短
12 生日高考祝福语妹妹简短
13 下飞机祝福语简短英文
14 元宵发客户祝福语简短
15 爸妈金婚文案祝福语简短
16 新郎朋友红包祝福语简短
17 虎年五一祝福语大全简短
18 出阁宴祝福语姐姐简短