node.js搭建本地服务器

node.js搭建本地服务器_第1张图片
c

文件目录下创建 http.js为服务器设置文件

var PORT = 3000;//

var http = require('http');

var url=require('url');

var fs=require('fs');

var mine=require('./mine').types;//

var path=require('path');

var server = http.createServer(function (request, response) {

var pathname = url.parse(request.url).pathname;

var realPath = path.join("webapp", pathname);    //这里设置自己的文件名称;

var ext = path.extname(realPath);

ext = ext ? ext.slice(1) : 'unknown';

fs.exists(realPath, function (exists) {

if (!exists) {

response.writeHead(404, {

'Content-Type': 'text/plain'

});

response.write("This request URL " + pathname + " was not found on this server.");

response.end();

} else {

fs.readFile(realPath, "binary", function (err, file) {

if (err) {

response.writeHead(500, {

'Content-Type': 'text/plain'

});

response.end(err);

} else {

var contentType = mine[ext] || "text/plain";

response.writeHead(200, {

'Content-Type': contentType

});

response.write(file, "binary");

response.end();

}

});

}

});

});

server.listen(PORT);

console.log("Server runing at port: " + PORT + ".");

mine.js 为 引入对应的文件

exports.types = {

"css": "text/css",

"gif": "image/gif",

"html": "text/html",

"ico": "image/x-icon",

"jpeg": "image/jpeg",

"jpg": "image/jpeg",

"js": "text/javascript",

"json": "application/json",

"pdf": "application/pdf",

"png": "image/png",

"svg": "image/svg+xml",

"swf": "application/x-shockwave-flash",

"tiff": "image/tiff",

"txt": "text/plain",

"wav": "audio/x-wav",

"wma": "audio/x-ms-wma",

"wmv": "video/x-ms-wmv",

"xml": "text/xml"

};

最后


服务器跑在 3000端口

http.js 中


这里写自己项目文件夹的名字

打开   http://localhost:3000/index.html

就可以看到自己的项目了

你可能感兴趣的:(node.js搭建本地服务器)