Serving static files in Express

To serve static files such as images, CSS files, and JavaScript files, use the express.static built-in middleware function in Express.

Pass the name of the directory that contains the static assets to the express.static middleware function to start serving the files directly. For example, use the following code to serve images, CSS files, and JavaScript files in a directory named public:

app.use(express.static('public'))

Now, you can load the files that are in the public directory:

http://localhost:3000/images/kitten.jpg
http://localhost:3000/css/style.css
http://localhost:3000/js/app.js
http://localhost:3000/images/bg.png
http://localhost:3000/hello.html
Express looks up the files relative to the static directory, so the name of the static directory is not part of the URL.

To use multiple static assets directories, call the express.static middleware function multiple times:

app.use(express.static('public'))
app.use(express.static('files'))

Express looks up the files in the order in which you set the static directories with the express.static middleware function.

To create a virtual path prefix (where the path does not actually exist in the file system) for files that are served by the express.static function,specify a mount path for the static directory, as shown below:

app.use('/static', express.static('public'))

Now, you can load the files that are in the public directory from the /static path prefix.

http://localhost:3000/static/images/kitten.jpg
http://localhost:3000/static/css/style.css
http://localhost:3000/static/js/app.js
http://localhost:3000/static/images/bg.png
http://localhost:3000/static/hello.html

However, the path that you provide to the express.static function is relative to the directory from where you launch your node process. If you run the express app from another directory, it’s safer to use the absolute path of the directory that you want to serve:

app.use('/static', express.static(path.join(__dirname, 'public')))

openshift上创建的node1.0工程样例中index.html引用的所有资源都是绝对地址,

为什么呢,因为它不知道我们的目录结构,也不想建一些我们不想要的目录,就空着了。

四处查询得出一个结论,必须得对静态文件目录作处理才能不至于404,而工程里只有一个server.js

#!/bin/env node
// OpenShift sample Node application
var express = require('express');
var fs = require('fs'); /**
* Define the sample application.
*/
var SampleApp = function() { // Scope.
var self = this; /* ================================================================ */
/* Helper functions. */
/* ================================================================ */ /**
* Set up server IP address and port # using env variables/defaults.
*/
self.setupVariables = function() {
// Set the environment variables we need.
self.ipaddress = process.env.OPENSHIFT_NODEJS_IP;
self.port = process.env.OPENSHIFT_NODEJS_PORT || 8080; if (typeof self.ipaddress === "undefined") {
// Log errors on OpenShift but continue w/ 127.0.0.1 - this
// allows us to run/test the app locally.
console.warn('No OPENSHIFT_NODEJS_IP var, using 127.0.0.1');
self.ipaddress = "127.0.0.1";
};
}; /**
* Populate the cache.
*/
self.populateCache = function() {
if (typeof self.zcache === "undefined") {
self.zcache = { 'index.html': '' };
} // Local cache for static content.
self.zcache['index.html'] = fs.readFileSync('./index.html');
}; /**
* Retrieve entry (content) from cache.
* @param {string} key Key identifying content to retrieve from cache.
*/
self.cache_get = function(key) { return self.zcache[key]; }; /**
* terminator === the termination handler
* Terminate server on receipt of the specified signal.
* @param {string} sig Signal to terminate on.
*/
self.terminator = function(sig){
if (typeof sig === "string") {
console.log('%s: Received %s - terminating sample app ...',
Date(Date.now()), sig);
process.exit(1);
}
console.log('%s: Node server stopped.', Date(Date.now()) );
}; /**
* Setup termination handlers (for exit and a list of signals).
*/
self.setupTerminationHandlers = function(){
// Process on exit and signals.
process.on('exit', function() { self.terminator(); }); // Removed 'SIGPIPE' from the list - bugz 852598.
['SIGHUP', 'SIGINT', 'SIGQUIT', 'SIGILL', 'SIGTRAP', 'SIGABRT',
'SIGBUS', 'SIGFPE', 'SIGUSR1', 'SIGSEGV', 'SIGUSR2', 'SIGTERM'
].forEach(function(element, index, array) {
process.on(element, function() { self.terminator(element); });
});
}; /* ================================================================ */
/* App server functions (main app logic here). */
/* ================================================================ */ /**
* Create the routing table entries + handlers for the application.
*/
self.createRoutes = function() {
self.routes = { }; self.routes['/asciimo'] = function(req, res) {
var link = "http://i.imgur.com/kmbjB.png";
res.send("<html><body><img src='" + link + "'></body></html>");
}; self.routes['/'] = function(req, res) {
res.setHeader('Content-Type', 'text/html');
res.send(self.cache_get('index.html') );
};
}; /**
* Initialize the server (express) and create the routes and register
* the handlers.
*/
self.initializeServer = function() {
self.createRoutes();
self.app = express.createServer(); // Add handlers for the app (from the routes).
for (var r in self.routes) {
self.app.get(r, self.routes[r]);
}
}; /**
* Initializes the sample application.
*/
self.initialize = function() {
self.setupVariables();
self.populateCache();
self.setupTerminationHandlers(); // Create the express server and routes.
self.initializeServer();
}; /**
* Start the server (starts up the sample application).
*/
self.start = function() {
// Start the app on the specific interface (and port).
self.app.listen(self.port, self.ipaddress, function() {
console.log('%s: Node server started on %s:%d ...',
Date(Date.now() ), self.ipaddress, self.port);
});
}; }; /* Sample Application. */ /**
* main(): Main code.
*/
var zapp = new SampleApp();
zapp.initialize();
zapp.start();

openshift - server.js

另一个例子

#!/bin/env node

var express = require('express'),
fs = require('fs'),
io, MongoClient = require('mongodb').MongoClient,
MONGODB_ITEMS_TO_LOAD_LIMIT = 50,
markdown = require("markdown").markdown; var MyApp = function() { var self = this;
self.setupVariables = function() {
self.appname = process.env.OPENSHIFT_APP_NAME || 'rtwc';
self.ipaddress = process.env.OPENSHIFT_INTERNAL_IP || process.env.OPENSHIFT_NODEJS_IP;
self.port = process.env.OPENSHIFT_INTERNAL_PORT || process.env.OPENSHIFT_NODEJS_PORT || 8082;
self.dbport = process.env.OPENSHIFT_MONGODB_DB_PORT || 27017;
self.dbname = self.appname; if (typeof self.ipaddress === "undefined") {
console.warn('No OPENSHIFT_NODEJS_IP var, using 127.0.0.1');
self.ipaddress = "127.0.0.1";
}
if (process.env.OPENSHIFT_MONGODB_DB_PASSWORD) {
console.log("We are in OpenShift");
self.connection_string = process.env.OPENSHIFT_MONGODB_DB_USERNAME + ":" +
process.env.OPENSHIFT_MONGODB_DB_PASSWORD + "@" +
process.env.OPENSHIFT_MONGODB_DB_HOST + ':' +
self.dbport + '/' +
self.dbname;
} else {
console.log("We are in localhost");
self.connection_string = 'admin:VVkkGUKNh2by@' + self.ipaddress + ':' + self.dbport + '/' + self.dbname;
}
}; /**
* Retrieve entry (content) from cache.
* @param {string} key Key identifying content to retrieve from cache.
*/
self.cache_get = function(key) {
return self.zcache[key];
}; /**
* terminator === the termination handler
* Terminate server on receipt of the specified signal.
* @param {string} sig Signal to terminate on.
*/
self.terminator = function(sig) {
if (typeof sig === "string") {
console.log('%s: Received %s - terminating sample app ...',
Date(Date.now()), sig);
process.exit(1);
}
console.log('%s: Node server stopped.', Date(Date.now()));
}; /**
* Setup termination handlers (for exit and a list of signals).
*/
self.setupTerminationHandlers = function() {
console.log("We are in localhost");
self.connection_string = 'admin:VVkkGUKNh2by@' + self.ipaddress + ':' + self.dbport + '/' + self.dbname;
};
}; /**
* Retrieve entry (content) from cache.
* @param {string} key Key identifying content to retrieve from cache.
*/
self.cache_get = function(key) {
return self.zcache[key];
}; /**
* terminator === the termination handler
* Terminate server on receipt of the specified signal.
* @param {string} sig Signal to terminate on.
*/
self.terminator = function(sig) {
if (typeof sig === "string") {
console.log('%s: Received %s - terminating sample app ...',
Date(Date.now()), sig);
process.exit(1);
}
console.log('%s: Node server stopped.', Date(Date.now()));
}; /**
* Setup termination handlers (for exit and a list of signals).
*/
self.setupTerminationHandlers = function() {
/**
* Create the routing table entries + handlers for the application.
*/
self.createRoutes = function() {
self.routes = {};
self.routes['/health'] = function(req, res) {
res.send('1');
}; self.routes['/asciimo'] = function(req, res) {
var link = "http://i.imgur.com/kmbjB.png";
res.send("<html><body><img src='" + link + "'></body></html>");
}; self.routes['/env'] = function(req, res) {
var content = 'Version: ' + process.version + '\n<br/>\n' +
'Env: {<br/>\n<pre>';
for (var k in process.env) {
content += ' ' + k + ': ' + process.env[k] + '\n';
}
content += '}\n</pre><br/>\n';
res.send(content);
res.send('<html>\n' +
' <head><title>Node.js Process Env</title></head>\n' +
' <body>\n<br/>\n' + content + '</body>\n</html>');
};
self.routes['/'] = function(req, res) {
res.render('page'); // page.jade is our template
}; }; /**
* Initialize the server (express), create the routes and register
* the handlers.
*/
self.initializeServer = function() {
self.createRoutes();
self.app = express();
self.app.set('views', __dirname + '/tpl');
self.app.set('view engine', 'jade');
self.app.engine('jade', require('jade').__express);
for (var r in self.routes) {
self.app.get(r, self.routes[r]);
} self.app.use(express.static(__dirname + '/public'));
self.app.use('/docs', express.static(__dirname + '/docs'));
}; /**
* Initializes the sample application.
*/
self.initialize = function() {
self.setupVariables();
/*self.populateCache();*/
self.setupTerminationHandlers();
self.initializeServer(); }; /**
* Start the server (starts up the sample application).
*/
self.start = function() {
io = require('socket.io').listen(
self.app.listen(self.port, self.ipaddress, function() {
console.log('%s: Node server started on %s:%d ...',
Date(Date.now()), self.ipaddress, self.port);
}));
io.sockets.on('connection', function(socket) {
socket.emit('connected', { id: socket.id });
console.log("Socket with ID %s connected on %s",
socket.id, new Date());
socket.on('recognizing user', function(user) { if (user.isNewish) {
socket.set('nickname', user.name);
} io.sockets.emit('user recognized', user); });
MongoClient.connect('mongodb://' + self.connection_string, function(err, db) {
if (err) throw err;
db.collection('messages').find().sort({ $natural: -1 }).limit(MONGODB_ITEMS_TO_LOAD_LIMIT).toArray(function(err, docs) {
if (err) throw err;
socket.emit('messages loaded', docs.reverse());
db.close();
});
}); socket.on('set nickname', function(user) {
socket.set('nickname', user.newName, function() {
socket.broadcast.emit('nickname set', user);
socket.emit('nickname set', user);
});
}); socket.on('writing', function(data) {
this.broadcast.emit('written', data);
}); socket.on('send message', function(data) {
data.text = markdown.toHTML(data.text);
io.sockets.emit('message', data);
MongoClient.connect('mongodb://' + self.connection_string, function(err, db) {
if (err) throw err;
db.collection('messages').insert(data, { w: 1 }, function(err, result) {
if (err) throw err;
console.log("Message saved:");
console.log(data);
db.close();
});
});
}); socket.on('disconnect', function() {
socket.get('nickname', function(err, name) {
if (err) throw err;
socket.broadcast.emit('disconnected', {
id: socket.id,
name: name
});
console.log("%s (%s) disconnected. %s", name, socket.id, new Date());
});
});
}); }; }; /* End of application. */ /**
* main(): Main code.
*/
var server = new MyApp();
server.initialize();
server.start();

server.js

参看这篇文章,以及上面的写法:

Express细节探究(1)——app.use(express.static)

//尝试了文中最后一句'/static'终于奇迹般的加载成功了! 最后改为常见的当前路径'/'
self.initializeServer = function() {
self.createRoutes();
self.app = express.createServer();
self.app.use('/', express.static(__dirname + '/web')); // Add handlers for the app (from the routes).
for (var r in self.routes) {
self.app.get(r, self.routes[r]);
}
};
//使用"/"表示静态资源目录'/web'

其实也就在openshift的sample上加了一行代码,没倒腾过服务器可把我坑了几个小时。。

一般的部署教程到后面都是讲数据库,都没人care这个简单的问题。

html里面这么引用就可以了,不用省了/web/...还搞一个/static/...替代它。

<script src="/html/js/lib/createjs-2015.11.26.min.js"></script>

另一篇通俗的阐述了为什么不能直接读取html中制定的资源。

nodejs对静态文件目录的处理的更多相关文章

  1. Django基础,Day9 - 静态文件目录与路径设置说明(eg. images, JavaScript, CSS)

    静态文件路径设置官方说明 1. Make sure that django.contrib.staticfiles is included in your INSTALLED_APPS. 2. In ...

  2. app.use(express.static)设置静态文件目录小解

    app.use(path, function, [, function]) 功能: 为path注册中间函数,即根据path使用不同函数进行处理,默认path是"/",也就是处理任何 ...

  3. Asp.Net Core 静态文件目录操作

    一.默认静态文件处理 Asp.Net Core的默认处理方式,将所有的静态文件都放在wwwroot文件夹中 1.默认配置,在启动文件Startup中 public void Configure(IAp ...

  4. Asp.net core静态文件目录访问

    Asp.net core静态文件目录访问 如果使用Asp.net core来实现一个能够访问其它电脑上的资源 新建工程 选择项目框架 如何将静态文件注入到项目中 在startup.cs文件的Confi ...

  5. asp.net core 之静态文件目录的操作

    文章前言 之前写了一篇关于模拟登录的文章,自我感觉内容不太丰富,今天的这篇文章,希望在内容上能丰富些.本人缺少写文章的经验,技术上也是新手,但我会努力的,希望大家多多支持小弟. asp.net cor ...

  6. nodejs http静态服务器

    使用nodejs写的很简单的静态服务器,没有做cluster处理,没有做缓存处理,不支持访问文件夹,功能只有一个,就是获取到文件后再返回文件内容. var fs = require('fs'); va ...

  7. Nodejs之静态资源处理

    前言 着眼于问题 重现问题 indexhtml indexcss serverjs 发现问题 解决问题 serverjs express 核心 server-expressjs indexhtml 总 ...

  8. nodejs之静态文件托管、 路 由、EJS 模板引擎、GET、POST

    1.静态文件托管 静态文件托管:是指对于一个js方法进行封装,提高代码可读性 //fs模块 var fs=require('fs'); //path模块 var path=require('path' ...

  9. nodejs express 静态文件的路径

    当express 设置为静态文件服务器的时候.可以通过2种方式进行方位: 1,通过设置app.use('路径1','../a/b/image') express 路径的形式,如 src="路 ...

随机推荐

  1. Android(java)学习笔记211:采用httpclient提交数据(qq登录案例)

    1.Apache -Httpclient HttpClient 是 Apache Jakarta Common 下的子项目,可以用来提供高效的.最新的.功能丰富的支持 HTTP 协议的客户端编程工具包 ...

  2. 初识jsp

    复习: 1.servlet生命周期: (1)默认是以第一次请求的时候创建并初始化Servlet,而且只做一次.(构造函数 init()) web.xml(配置后,是可以达到在服务启动后,立刻进行ser ...

  3. 深入理解计算机系统第二版习题解答CSAPP 2.1

    A.将0x39A7F8转换为二进制. 0011 1001  1010 0111  1111 1000 B.将二进制1100 1001 0111 1011转换为十六进制. 0xC97B C.将0xD5E ...

  4. 在虚拟机安装64位系统提示,此主机支持Intel VT-x,但Intel VT-x处于禁用状态

    进入BIOS - Security - Virtualization - Intel (R) Virtualization Technology 将 Disabled 改为 Enabled 即可

  5. 16Aspx.com源码2013年10月到2013年12月详细

    创建时间FROM: 创建时间TO:   ExtJS合同管理信息系统源码 2013-12-13   [VS2008] 源码介绍: ExtJS合同管理信息系统源码浏览器兼容:IE,Firefox,谷歌等主 ...

  6. ios专题 - 异步下载加下载进度显示

    [罗国强原创] 今天被刺激了,愤概地要写下这边博文. 说到http异步下载,首先要知道其中的关键类. 关键类是NSURLConnection  NSURLRequest NSMutableURLReq ...

  7. C++指针学习笔记

    本文参考http://www.prglab.com/cms/pages/c-tutorial/advanced-data/pointers.php 1.存储其它变量地址的变量(如下面例子中的addre ...

  8. VS2010配置目录,解决:error MSB6006: “CL.exe”已退出,代码为 5问题

    配置属性->VC++目录 可执行文件目录:$(VCInstallDir)bin;$(WindowsSdkDir)bin\NETFX 4.0 Tools;$(WindowsSdkDir)bin;$ ...

  9. ios 64位下编译webrtc的libvpx库出现错误Bad cputype for object file.Currently only tested for CPU_TYPE_x86_64

    diff --git a/libvpx.gyp b/libvpx.gypindex 4f8cb2b..4eb6866 100644--- a/libvpx.gyp+++ b/libvpx.gyp@@ ...

  10. mysql主从 1050错误

    在mysql从库上查询时出现如下错误 ...................... Last_Errno: 1050                    Last_Error: Error 'Tab ...