首先确保你现在已经安装了node环境
检测方法:命令行输入npm -v
如上图所示,表示已经安装咯!
搭建静态服务器
//首先引入以下四个模块:
const http = require('http'); //http 请求模块
const fs = require('fs'); //文件访问模块
const url = require('url'); //url地址模块
const path = require('path'); //绝对路径模块
let port = '';
//开启一个node服务
let server = http.createServer(function(request, response){
//获取输入的url解析后的对象
let pathObj = url.parse(request.url, true);
//static文件夹的绝对路径,请求静态资源
let staticPath = path.resolve(__dirname, 'static')
//获取资源文件绝对路径
let filePath = path.join(staticPath, pathObj.pathname)
//异步读取file, 默认访问index.html页面,
// 然后可以输入 /html/index2.html 或者 /images/st.jpg 或者 /js/aaa.js 等
if(request.url == '/' || request.url == ''){
fs.readFile('./static/html/index.html', function(err, data){
if(!err){
response.writeHead(200, {"Content-Type": "text/html;charset=UTF-8"});
response.end(data)
}else{
throw err;
}
});
}else{
fs.readFile(filePath, 'binary', function(err, fileContent){
if(err){
console.log('404')
response.writeHead(404, 'not found')
response.end('<h1>404 Not Found</h1>')
}else{
console.log('ok')
response.write(fileContent, 'binary')
response.end()
}
})
}
//制定服务port地址
port = 3000;
server.listen(port);
console.log('view http://localhost:' + port);
});
如需源码请点击此处下载 点击下载源码