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

 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"
};

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

node http.js 

浏览器中输入:

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

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

上一篇:OracleGateway11gR2访问异构数据库(MSSQL)配置文档(转)


下一篇:(转)关于linux挂载window下共享文件