'use strict'
var url = require('url');
var path = require('path');
var fs = require('fs');
var http = require('http');
//get the current path
//var root = path.resolve('.');//以当前的目录为服务器的根目录
var root = path.resolve(process.argv[2] || '.');//以输入的参数作为服务器的根目录,如果没有输入参数就将当前目录作为服务器根目录
console.log('local root dir :' + root);
//create server
var server = http.createServer(function(request, response) {
//get the path of URL
var pathname = url.parse(request.url).pathname;
//get the local path
var filepath = path.join(root, pathname);
//get the file stat and output the request file by callback function
fs.stat(filepath, function(err, stat) {
if(!err && stat.isFile()) {
console.log('200' + request.url);
response.writeHead(200);
fs.createReadStream(filepath).pipe(response);//没有必要手动读取文件内容。由于response对象本身是一个Writable Stream,直接用pipe()方法就实现了自动读取文件内容并输出到HTTP响应。
} else {
console.log('404' + request.url);
response.writeHead(404);
response.end('404 Not Found');
}
});
});
server.listen(8080);
console.log('Server is running at http://127.0.0.1:8080/');
path.resolve() 路径寻航(这名字不错) path.resolve([from…], to)
path.resolve('foo/bar', '/tmp/file/', '..', 'a/../subfile')
//相当于:
cd foo/bar
cd /tmp/file/
cd ..
cd a/../subfile1
path.join([path1],path[2]...) 路径合并
path.join('///foo', 'bar', '//baz/asdf', 'quux', '..');
=>'/foo/bar/baz/asdf'
path.normalize('/foo/bar//baz/asdf/quux/..');
=> '/foo/bar/baz/asdf'
response.end([data], [encoding])
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有