引入http基本模块实现服务
var http = require('http');
//文件读写模块
var fs = require('fs');
//路径相关模块
var path = require('path');
http.createServer(function(req, res){
if(req.url === '/'){
//输出内容并结束响应,这两行可以合成end('hello index')
// res.write('hello index');
// res.end();
res.setHeader('Content-Type','text/plain; charset=utf-8');
res.end('hello,<h1>我的主页</h1>');
}else if(req.url === '/test'){
//直接响应html
res.setHeader('Content-Type','text/html; charset=utf-8');
res.end('hello <h1>test</h1>');
}else if(req.url === '/page'){
//响应html文件
//__dirname表示当前文件所在的文件夹绝对路径,__filename为当前文件绝对路径,非全局
//类似于沙箱操作的参数(function(__dirname,__filename){...})('文件夹路径','文件路径')
//path.join这一语句输出d:/nodespace/test/htmls/main.html,屏蔽了不同系统分隔符的区别
//如果出现异常,err不为空
fs.readFile(path.join(__dirname,'htmls','main.html'),function(err,data){
//遇到异常直接抛出去
if(err){
throw err;
}
//把读取到的html文件直接返回给浏览器
res.end(data);
})
}else{
res.end('not found!')
}
}).listen(8080, function(){
console.log('server is running...')
})
加载静态资源文件,首先要安装mime模块,主要是根据后缀识别类型
安装和使用:https://www.npmjs.com/package/mime
image.png