搭建本地nodeJs服务器

来源:互联网 发布:淘宝虚假订单不清洗 编辑:程序博客网 时间:2024/06/08 00:00

这里关于nodeJs环境的搭建就不再赘述了。

目录结构

这里是我的项目中大概的目录结构,其实说明的主要是一个相对路径的关系,具体放在什么地方都可以

——bin
          |__mine.js
          |__server.js
——build
          |__index.html

废话不多说,直接上代码,一些重要的店在注释中写了:

代码

server.js:

var PORT = 3000;//这里设置的是端口号,访问url:localhost:3000var http = require('http');var url=require('url');var fs=require('fs');var mine=require('./mine').types; //同级目录下的mine.js文件,需要node支持的文件类型。var path=require('path');var server = http.createServer(function (request, response) {    var pathname = url.parse(request.url).pathname;    //这里是配置项目文件路径,比如说我的项目是在build目录下面,build和bin是同级别关系,所以../build进入文件,这样配置之后在浏览器中访问的url则是:localhost:3000/index.html,有其他文件或者文件夹相应加上目录即可。    var realPath = path.join("../build", pathname);    //console.log(realPath);    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"};

使用

使用命令行切换到bin目录下

cd bin/node server.js

随即会显示Server runing at port: 3000.

0 0
原创粉丝点击