服务器端node.js
实现一个文件服务器 var fs = require('fs'); var url = require('url'); var path = require('path'); var http = require('http'); // 从命令行参数获取根目录,默认为当前目录 var root = path.resolve(process.argv[2]||'.'); // 创建服务器 var server = http.createServer(function(req,res) { var pathname = url.parse(req.url).pathname; var filepath = path.join(root,pathname); //获取文件状态 fs.stat(filepath,function(err,stats){ if(!err && stats.isFile()) { res.writeHead(200); // 将文件流导向res fs.createReadStream(filepath).pipe(res); } else { // 发送404响应 res.writeHead(404); res.end('404 Not Found'); } }) }); server.listen(8080); console.log('server is running at http://127.0.0.1:8080/');