代码:
var http = require('http'); var url = require('url'); var fs = require('fs'); //涉及文件读取 http.createServer(function (req, res, next) { var pathname = url.parse(req.url).pathname; ///结尾的请求,自动添加上”index.html if (pathname.slice(-1) === "/") { pathname = pathname + 'index.html'; } var path = __dirname + pathname; var exists = fs.existsSync(path) if (exists) { var stat = fs.statSync(path); if (stat.isFile()) { fs.readFile(path, function (err, data) { res.write(data); res.end(); }); } else { //不是文件一律输出403 res.writeHead(403); res.end('403 This path cannot be accessed') } } else { res.writeHead(404); res.end('404 not found.') } }).listen(3000, function () { console.log('listen http://localhost:3000') });
本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。
我来说两句