需求:
搭建本地的文件服务器,
打开浏览器输入http://localhost:8080
默认打开index.html
,
输入http://localhost:8080/hello.txt
网页打开hello.txt
内容,
如果没有该文件则显示404。
"use strict";
var fs = require("fs");
var url = require("url");
var path = require("path");
var http = require("http");
//从命令行参数获取root目录,默认是当前目录
var root = path.resolve(process.argv[2]||".");
//创建服务器
var server = http.createServer(function(request,response){
//获得url的path
var filename = url.parse(request.url).pathname;
//如没有path,设置默认
if("/"==filename){filename = "index.html";}
//获得对应的本地文件路径
var filepath = path.join(root,filename);
//获取文件状态:
fs.stat(filepath,function(err,stats){
if(!err&&stats.isFile()){
console.log(200);
response.writeHead(200,{"content-type":"text/html;charset=utf8"});
fs.createReadStream(filepath).pipe(response);
} else if(!err&&stats.isDirectory()){
console.log(404);
response.writeHead(404);
//将文件源导向response
response.end("Please open a file, not a directory");
}else{
console.log(404);
response.writeHead(404);
response.end("404 Not Found!");
}
})
});
server.listen(8080);
console.log("Server is running ... ");