通过NodeJS加载JS文件和HTML文件的正确方法

我不能得到所服务的defualt.htm页面头部的内容“工作”。 在DOM加载的HTML,只是CSS和JS文件失败。 有更好的select吗? 编号喜欢保持在NodeJS内的解决scheme,但也可以打开socket.io并表示。

谢谢,下面是即时通讯使用。

NodeJS服务页面

var http = require('http'), fs = require('fs'); fs.readFile(__dirname+'/default.htm', function (err, html) { if (err) { throw err; } http.createServer(function(request, response) { response.writeHeader(200, {"Content-Type": "text/html"}); response.write(html); response.end(); }).listen(port.number); }); 

Default.html页面

 <!DOCTYPE html> <html> <head lang="en"> <meta charset="utf-8" /> <title></title> <link rel="stylesheet" href="objects/css/site.css" type="text/css" /> <script src="objects/js/jquery.min.js" type="text/javascript"></script> <script src="objects/js/site.min.js" type="text/javascript"></script> </head> <body></body> </html> 

我也要把我的两分钱也扔在这里。

我用静态文件解决同样的问题的方式是我开始使用Paperboy模块,现在已经不推荐使用Send模块了。

Anyhoo,我解决这个问题的方法是在请求进入我的GET方法之前“劫持”请求并检查它的path。

我“劫持”的方式如下

 self.preProcess(self, request, response); 

 preProcess: function onRequest(app, request, response){ //DO STUFF } 

如果path包含STATICFILES目录,我会做一个不同的文件服务,否则我会去与“HTML”path。 以下是preProcess()函数的//DO STUFF

 var path = urllib.parse(request.url).pathname; if(path.indexOf(settings.STATICFILES_DIR) != -1) { path = settings.STATICFILES_DIR; requestedFile = request.url.substring(request.url.lastIndexOf('/') + 1, request.url.length); return resolver.resolveResourceOr404(requestedFile, request, response); } 

这样做可能有更好的方法,但是这对于我所需要做的事情来说就像是一种魅力。

然后使用Paperboy模块,使用resolver.resolveResourceOr404(); 函数像这样传递文件

 resolveResourceOr404 : function (filename, httpRequest, httpResponse) { var root = path.join(path.dirname(__filename), ''); paperboy.deliver(root, httpRequest, httpResponse) .error(function(e){ this.raise500(httpResponse); }) .otherwise(function(){ this.raise404(httpResponse); }); } 

你的Javascript和风格失败,因为它们不存在。 您当前的networking服务器只发送一个路由,即根路由。 相反,你需要允许使用多个路线。 ExpressJS以更简单的方式为您做到这一点,但是如果没有它,还是很有可能的。

  var http = require('http'); var fs = require('fs'); var server = http.createServer(function(request, response){ var header_type = ""; var data = ""; var get = function (uri, callback) { // match `request.url` with uri with a regex or something. var regex = uri; if (request.url.match(regex)) { callback(); } }; var render = function (resource) { // resource = name of resource (ie index, site.min, jquery.min) fs.readFile( __dirname + "/" + resource, function(err, file) { if (err) return false; // Do something with the error.... header_type = ""; // Do some checking to find out what header type you must send. data = file; } }; get('/', function(req, res, next) { // Send out the index.html render('index.html'); next(); }); get('/javascript.min', function(req, res, next) { render('javascript.js'); next(); }); }); server.listen(8080); 

这可能会让你开始,但你必须自己实现一些像next()东西。 一个非常简单的解决scheme,但一个工作。

响应静态文件的另一个解决scheme是在http.createServercallback中创build一个捕获器。 在get方法中,如果uris不匹配,那么您将在与文件系统结构完整URI相匹配的公用文件夹中查找。

那么,你正在为所有请求提供你的default.htm文件。 所以,当浏览器要求objects/js/jquery.min.js ,你的服务器返回default.htm的内容。

你应该真的考虑使用快递或其他框架。

使用Express来处理这种东西最好。

像这样的东西会做这个工作。

App.js

 var express = require('express') , http = require('http') , path = require('path'); var app = express(); //Configure Your App and Static Stuff Like Scripts Css app.configure(function(){ app.set('port', process.env.PORT || 3000); app.set('views', __dirname + '/views'); // Your view folder app.set('view engine', 'jade'); //Use jade as view template engine // app.set("view options", {layout: false}); // app.engine('html', require('ejs').renderFile); //Use ejs as view template engine app.use(express.logger('dev')); app.use(express.bodyParser()); app.use(express.methodOverride()); app.use(express.cookieParser()); app.use(app.router); app.use(require('stylus').middleware(__dirname + '/public')); //Use Stylus as the CSS template engine app.use(express.static(path.join(__dirname, 'public'))); //This is the place for your static stuff }); app.get('/',function(req,res){ res.render('index.jade',{ title:"Index Page } }); 

索引是一个玉的模板页面。它呈现为静态html,并且用expressperformance很好。

对于所有页面的全局静态页眉,您可以创build一个像这样的模板并将其包含在任何页面中。

static_header.jade

  doctype 5 html head title= title script(src='/javascripts/jquery-1.8.2.min.js') block header link(rel='stylesheet', href='/stylesheets/style.css') body block content 

最后是你的index.jade,它使用static_header和自己的dynamic头与自己的脚本。

 extends static_header block header script(src='/javascripts/jquery-ui-1.9.1.custom.js') script(src='http://jquery-ui.googlecode.com/svn/trunk/ui/i18n/jquery.ui.datepicker-tr.js') link(rel='stylesheet',href='/stylesheets/jquery-ui-1.9.1.custom.min.css') block content h1= title 

把这两个文件在您的视图文件夹,并准备滚动。

那么试试这个:

 var http = require('http'); var fs = require('fs'); var path = require('path'); http.createServer(function (request, response) { console.log('request starting...'); var filePath = '.' + request.url; if (filePath == './') filePath = './index.html'; var extname = path.extname(filePath); var contentType = 'text/html'; switch (extname) { case '.js': contentType = 'text/javascript'; break; case '.css': contentType = 'text/css'; break; case '.json': contentType = 'application/json'; break; case '.png': contentType = 'image/png'; break; case '.jpg': contentType = 'image/jpg'; break; case '.wav': contentType = 'audio/wav'; break; } fs.readFile(filePath, function(error, content) { if (error) { if(error.code == 'ENOENT'){ fs.readFile('./404.html', function(error, content) { response.writeHead(200, { 'Content-Type': contentType }); response.end(content, 'utf-8'); }); } else { response.writeHead(500); response.end('Sorry, check with the site admin for error: '+error.code+' ..\n'); response.end(); } } else { response.writeHead(200, { 'Content-Type': contentType }); response.end(content, 'utf-8'); } }); }).listen(8125); console.log('Server running at http://127.0.0.1:8125/');