主要思想就是任何一个静态文件也应该作响应,一个获取静态文件都应当请求来处理,这是主要思想。javascript
同时要注意两点。第一,对于不一样的文件类型,好比html,css,js,请求头里面的文件类型须要根据不一样的文件类型注明,css
第二,文件的路径须要表达准确,fs.readFile方法的第一个参数path是已起服务的文件为根目录,这里就是以server.js文件的所在目录为根目录html
文件目录vue
文件夹publicjava
Index.htmlnode
Css文件夹浏览器
Reset.css服务器
Index.cssapp
Js文件夹post
vue.min.js
Index.js
Server.js
Server.js和文件夹publi同级
来看server.js代码
var http = require('http');
var fs = require('fs');
var url = require('url');
// 建立服务器
http.createServer( function (request, response) {
// 解析请求,包括文件名
var pathname = url.parse(request.url).pathname;
var postfix = pathname.match(/(\.[^.]+|)$/)[0];//取得后缀名
// 输出请求的文件名
console.log("Request for " + pathname + " received.");
// 从文件系统中读取请求的文件内容
fs.readFile(pathname.substr(1), function (err, data) {
if (err) {
console.log(err);
// HTTP 状态码: 404 : NOT FOUND
// Content Type: text/plain
response.writeHead(404, {'Content-Type': 'text/html; charset=utf-8'});
}else{
// HTTP 状态码: 200 : OK
// Content Type: text/plain
console.log(postfix);
if(postfix==='html'){
response.writeHead(200, {'Content-Type': 'text/html'});
}else if(postfix==='css'){
response.writeHead(200, {'Content-Type': 'text/css'});
}
else if(postfix==='js'){
response.writeHead(200, {'Content-Type': 'application/javascript'});
}else{
}
// 响应文件内容
response.write(data.toString());
}
// 发送响应数据
response.end();
});
}).listen(8080);
// 控制台会输出如下信息
console.log('Server running at http://127.0.0.1:8080/');
最后在命令行输入node server.js 把服务器起起来
而后在浏览器打开http://127.0.0.1:8080/public/index.html