Fork me on GitHub

nodejs运行前端项目

有时候我们会创建一些小项目,只有几个简单html,没有引入一些前端框架,也没有使用webpack,那我们要如何让代码在我们本地跑起来呢?

当然是有很多种方法,IIS、wampserver等等好多都可以用,这里只是说道纯粹用node就把项目跑起来,配置简单。

前提是你要安装好了nodejs,安装方法,去百度一下大把。

现在假设你的文件目录如下

  • index
    • templates
      • index.html
    • static
      • js
        • index.js
      • css  
        • index.css

 

现在需要在index同级目录新建两个文件server.js:

var PORT = 8089;//监听的端口

var http = require('http');
var url=require('url');
var fs=require('fs');
var help=require('./help').types;//
var path=require('path');

var server = http.createServer(function (request, response) {
    var pathname = url.parse(request.url).pathname;
    var realPath = path.join("index", 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 = help[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 + ".");

help.js

 1 exports.types = {
 2   "css": "text/css",
 3   "gif": "image/gif",
 4   "html": "text/html",
 5   "ico": "image/x-icon",
 6   "jpeg": "image/jpeg",
 7   "jpg": "image/jpeg",
 8   "js": "text/javascript",
 9   "json": "application/json",
10   "pdf": "application/pdf",
11   "png": "image/png",
12   "svg": "image/svg+xml",
13   "swf": "application/x-shockwave-flash",
14   "tiff": "image/tiff",
15   "txt": "text/plain",
16   "wav": "audio/x-wav",
17   "wma": "audio/x-ms-wma",
18   "wmv": "video/x-ms-wmv",
19   "xml": "text/xml"
20 };

然后再index文件夹的同级目录下运行:

node http.js 

浏览器中输入:

http://localhost:8089/templates/index.html

就可以打开你的项目了,只是没有热更新,要手动刷新,但起码跑起来了

 

posted @ 2017-11-03 17:03  Tonny的学习笔记  阅读(20342)  评论(0编辑  收藏  举报