I want to use connect's vhost functionality to deploy several express.js apps to my dev vps. Here is my server.js file that is supposed to send requests to the appropriate place:
var express = require('express')
var quotes = require('quote-of-the-day/lib/app.js');
var server = express();
server.use(express.vhost('inspiringquoteoftheday.com',quotes));
server.listen(80);
Running node server.js throws this error:
Error: Cannot find module 'quote-of-the-day/lib/app.js'
Even though I can cd into app.js straight from the directory where server.js is located.
Here is the lib/app.js file in which I export my express app (I think)
// Generated by CoffeeScript 1.3.3
(function() {
var app, express, pub;
express = require('express');
module.exports = app = express();
pub = __dirname + '/public';
app.use(express["static"](pub));
app.use(express.errorHandler());
app.use(app.router);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.get('/', function(req, res) {
return res.render('home');
});
}).call(this);
Assuming a directory structure that looks something like this:
|-. quote-of-the-day
|-- server.js <-- the file you list in your question
|-. lib
|-- app.js
Then you should require your app.js with
require('./lib/app');
Might be helpful to use the __dirname global variable here.
it provides 'the name of the directory that the currently executing script resides in.'
thus you could do:
var otherApp = require(__dirname + 'quote-of-the-day/lib/app.js')
http://nodejs.org/docs/latest/api/globals.html
Related
I want to serve index.html and /media subdirectory as static files. The index file should be served both at /index.html and / URLs.
I have
web_server.use("/media", express.static(__dirname + '/media'));
web_server.use("/", express.static(__dirname));
but the second line apparently serves the entire __dirname, including all files in it (not just index.html and media), which I don't want.
I also tried
web_server.use("/", express.static(__dirname + '/index.html'));
but accessing the base URL / then leads to a request to web_server/index.html/index.html (double index.html component), which of course fails.
Any ideas?
By the way, I could find absolutely no documentation in Express on this topic (static() + its params)... frustrating. A doc link is also welcome.
If you have this setup
/app
/public/index.html
/media
Then this should get what you wanted
var express = require('express');
//var server = express.createServer();
// express.createServer() is deprecated.
var server = express(); // better instead
server.configure(function(){
server.use('/media', express.static(__dirname + '/media'));
server.use(express.static(__dirname + '/public'));
});
server.listen(3000);
The trick is leaving this line as last fallback
server.use(express.static(__dirname + '/public'));
As for documentation, since Express uses connect middleware, I found it easier to just look at the connect source code directly.
For example this line shows that index.html is supported
https://github.com/senchalabs/connect/blob/2.3.3/lib/middleware/static.js#L140
In the newest version of express the "createServer" is deprecated. This example works for me:
var express = require('express');
var app = express();
var path = require('path');
//app.use(express.static(__dirname)); // Current directory is root
app.use(express.static(path.join(__dirname, 'public'))); // "public" off of current is root
app.listen(80);
console.log('Listening on port 80');
express.static() expects the first parameter to be a path of a directory, not a filename. I would suggest creating another subdirectory to contain your index.html and use that.
Serving static files in Express documentation, or more detailed serve-static documentation, including the default behavior of serving index.html:
By default this module will send “index.html” files in response to a request on a directory. To disable this set false or to supply a new index pass a string or an array in preferred order.
res.sendFile & express.static both will work for this
var express = require('express');
var app = express();
var path = require('path');
var public = path.join(__dirname, 'public');
// viewed at http://localhost:8080
app.get('/', function(req, res) {
res.sendFile(path.join(public, 'index.html'));
});
app.use('/', express.static(public));
app.listen(8080);
Where public is the folder in which the client side code is
As suggested by #ATOzTOA and clarified by #Vozzie, path.join takes the paths to join as arguments, the + passes a single argument to path.
const path = require('path');
const express = require('express');
const app = new express();
app.use(express.static('/media'));
app.get('/', (req, res) => {
res.sendFile(path.resolve(__dirname, 'media/page/', 'index.html'));
});
app.listen(4000, () => {
console.log('App listening on port 4000')
})
If you have a complicated folder structure, such as
- application
- assets
- images
- profile.jpg
- web
- server
- index.js
If you want to serve assets/images from index.js
app.use('/images', express.static(path.join(__dirname, '..', 'assets', 'images')))
To view from your browser
http://localhost:4000/images/profile.jpg
If you need more clarification comment, I'll elaborate.
use below inside your app.js
app.use(express.static('folderName'));
(folderName is folder which has files) - remember these assets are accessed direct through server path (i.e. http://localhost:3000/abc.png (where as abc.png is inside folderName folder)
npm install serve-index
var express = require('express')
var serveIndex = require('serve-index')
var path = require('path')
var serveStatic = require('serve-static')
var app = express()
var port = process.env.PORT || 3000;
/**for files */
app.use(serveStatic(path.join(__dirname, 'public')));
/**for directory */
app.use('/', express.static('public'), serveIndex('public', {'icons': true}))
// Listen
app.listen(port, function () {
console.log('listening on port:',+ port );
})
I would add something that is on the express docs, and it's sometimes misread in tutorials or others.
app.use(mountpoint, middleware)
mountpoint is a virtual path, it is not in the filesystem (even if it actually exists). The mountpoint for the middleware is the app.js folder.
Now
app.use('/static', express.static('public')`
will send files with path /static/hell/meow/a.js to /public/hell/meow/a.js
This is the error in my case when I provide links to HTML files.
before:
<link rel="stylesheet" href="/public/style.css">
After:
<link rel="stylesheet" href="/style.css">
I just removed the static directory path from the link and the error is gone. This solves my error one thing more don't forget to put this line where you are creating the server.
var path = require('path');
app.use(serveStatic(path.join(__dirname, 'public')));
You can achieve this by just passing the second parameter express.static() method to specify index files in the folder
const express = require('express');
const app = new express();
app.use(express.static('/media'), { index: 'whatever.html' })
I want to serve index.html and /media subdirectory as static files. The index file should be served both at /index.html and / URLs.
I have
web_server.use("/media", express.static(__dirname + '/media'));
web_server.use("/", express.static(__dirname));
but the second line apparently serves the entire __dirname, including all files in it (not just index.html and media), which I don't want.
I also tried
web_server.use("/", express.static(__dirname + '/index.html'));
but accessing the base URL / then leads to a request to web_server/index.html/index.html (double index.html component), which of course fails.
Any ideas?
By the way, I could find absolutely no documentation in Express on this topic (static() + its params)... frustrating. A doc link is also welcome.
If you have this setup
/app
/public/index.html
/media
Then this should get what you wanted
var express = require('express');
//var server = express.createServer();
// express.createServer() is deprecated.
var server = express(); // better instead
server.configure(function(){
server.use('/media', express.static(__dirname + '/media'));
server.use(express.static(__dirname + '/public'));
});
server.listen(3000);
The trick is leaving this line as last fallback
server.use(express.static(__dirname + '/public'));
As for documentation, since Express uses connect middleware, I found it easier to just look at the connect source code directly.
For example this line shows that index.html is supported
https://github.com/senchalabs/connect/blob/2.3.3/lib/middleware/static.js#L140
In the newest version of express the "createServer" is deprecated. This example works for me:
var express = require('express');
var app = express();
var path = require('path');
//app.use(express.static(__dirname)); // Current directory is root
app.use(express.static(path.join(__dirname, 'public'))); // "public" off of current is root
app.listen(80);
console.log('Listening on port 80');
express.static() expects the first parameter to be a path of a directory, not a filename. I would suggest creating another subdirectory to contain your index.html and use that.
Serving static files in Express documentation, or more detailed serve-static documentation, including the default behavior of serving index.html:
By default this module will send “index.html” files in response to a request on a directory. To disable this set false or to supply a new index pass a string or an array in preferred order.
res.sendFile & express.static both will work for this
var express = require('express');
var app = express();
var path = require('path');
var public = path.join(__dirname, 'public');
// viewed at http://localhost:8080
app.get('/', function(req, res) {
res.sendFile(path.join(public, 'index.html'));
});
app.use('/', express.static(public));
app.listen(8080);
Where public is the folder in which the client side code is
As suggested by #ATOzTOA and clarified by #Vozzie, path.join takes the paths to join as arguments, the + passes a single argument to path.
const path = require('path');
const express = require('express');
const app = new express();
app.use(express.static('/media'));
app.get('/', (req, res) => {
res.sendFile(path.resolve(__dirname, 'media/page/', 'index.html'));
});
app.listen(4000, () => {
console.log('App listening on port 4000')
})
If you have a complicated folder structure, such as
- application
- assets
- images
- profile.jpg
- web
- server
- index.js
If you want to serve assets/images from index.js
app.use('/images', express.static(path.join(__dirname, '..', 'assets', 'images')))
To view from your browser
http://localhost:4000/images/profile.jpg
If you need more clarification comment, I'll elaborate.
use below inside your app.js
app.use(express.static('folderName'));
(folderName is folder which has files) - remember these assets are accessed direct through server path (i.e. http://localhost:3000/abc.png (where as abc.png is inside folderName folder)
npm install serve-index
var express = require('express')
var serveIndex = require('serve-index')
var path = require('path')
var serveStatic = require('serve-static')
var app = express()
var port = process.env.PORT || 3000;
/**for files */
app.use(serveStatic(path.join(__dirname, 'public')));
/**for directory */
app.use('/', express.static('public'), serveIndex('public', {'icons': true}))
// Listen
app.listen(port, function () {
console.log('listening on port:',+ port );
})
I would add something that is on the express docs, and it's sometimes misread in tutorials or others.
app.use(mountpoint, middleware)
mountpoint is a virtual path, it is not in the filesystem (even if it actually exists). The mountpoint for the middleware is the app.js folder.
Now
app.use('/static', express.static('public')`
will send files with path /static/hell/meow/a.js to /public/hell/meow/a.js
This is the error in my case when I provide links to HTML files.
before:
<link rel="stylesheet" href="/public/style.css">
After:
<link rel="stylesheet" href="/style.css">
I just removed the static directory path from the link and the error is gone. This solves my error one thing more don't forget to put this line where you are creating the server.
var path = require('path');
app.use(serveStatic(path.join(__dirname, 'public')));
You can achieve this by just passing the second parameter express.static() method to specify index files in the folder
const express = require('express');
const app = new express();
app.use(express.static('/media'), { index: 'whatever.html' })
I'm having a problem connecting an express server with a gulp serve/r task. In order to send my views to the DOM, I need express to do that. I'd like my server to run as a gulp task. The server runs, however when I try to access my local url it runs an error in browser:
Error: Failed to lookup view "index" in views directory "C:\Users\User Name\Documents\project\src\scripts"
My app.js
var http = require('http');
var express = require('express');
var exphbs = require('express-handlebars');
var path = require('path');
var hbs = exphbs.create({ /* config */ });
var app = express();
//environment variable
var port = process.env.PORT || 8000;
// static files + template engine
app.engine('handlebars', hbs.engine);
app.set('view engine', 'handlebars');
app.set('views', path.join(__dirname, '../scripts'));
app.use('/public', express.static(__dirname + '/public'));
//http request method get json list
app.get('/', function(req, res) {
res.render('index');
});
app.listen(port);
My file structure looks like this:
project
|-- src
| |-- css
| |-- scripts
| |-- app.js
| |-- index.html
What am I missing?
You should change this:
app.set('views', path.join(__dirname, '../scripts'));
to this:
app.set('views', path.join(__dirname, '..'));
This is because the index.html file resides in the src directory which is a parent of the scripts directory from which the script is executed.
My project structure looks like this:
project
assets/images/
css/application.css
js/application.js
font
node_modules
index.html
server.js
package.json
My goal is to be able to run 'node server.js" in the project folder and have it serve on port 80. Going to localhost:80 or w.e would render the index.html along with its css/assets/js.
I've tried with connect, express and http but no luck...new to node.
Thanks!
First of all, change your structure:
project
assets/images/
assets/css/application.css
assets/js/application.js
assets/font
node_modules
views/index.html
server.js
package.json
First require some packages:
var express = require('express'),
app = express(),
path = require('path');
Them run in the terminal window:
npm install express
Them set up the configurations:
app.set('views', path.join(__dirname, 'views')); // This is to serve static files like html in the views folder
app.set('view engine', html); // your engine, you can use html, jade, ejs, vash, etc
app.set('port', process.env.PORT || 80); // set up the port to be production or 80.
app.set('env', process.env.NODE_ENV || 'development');
app.use(express.static(path.join(__dirname, 'assets'))); // // This is to serve static files like .css and .js, images, fonts in the assets folder
Them create your routes:
app.get('/', function(req, res) {
res.send('Hello word');
});
app.get('/something', function(req, res) {
res.send('Hei, this is something!!!');
});
If you want render the index, inside the views folder:
app.get('/index', function(req, res) {
res.render('index');
});
And finally:
app.listen(app.get('port'), function(req, res) {
console.log('Server listening at ' + app.get('port')');
});
Them access localhost:80/index
Put your assets and subdirs under ./public, then from top dir, add app.js:
var express = require('express');
var app = new express();
app.use(express.static(__dirname + '/public'));
app.listen(80, function () {
console.log('Server running...');
});
I'm writing a multi instance NodeJS application serving my Chrome extensions.
I think I got stuck in all that is related to subfolders, requiring and exporting modules.
Here's my app structure:
At the very bottom, I have start.js which bootstraps some major parts of the application like Express, models, views, controllers, routes, etc..
var express = require('express'),
http = require('http'),
arguments = process.argv.slice(2),
port = arguments[0] || 3000;
var app = express(),
server = app.listen(port),
io = require('socket.io' ).listen(server ),
routes = require('./config/routes')(app);
app.configure(function(){
"use strict";
app.set('views', __dirname + '/app/views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.static(__dirname + '/app/public'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
});
app.configure('development', function() {
"use strict";
app.use(express.errorHandler());
});
console.log('Server is running on port ' + port);
module.exports = app;
In root folder of app, I have the instance files themselves. Like app.js (main), dealer.js (dealer instance), etc...
I run them like this:
[deb0rian#localhost www.bkbot.org]$ node ./app/dealer.js 3003
app/dealer.js itself for now is pretty simple:
var app = require('../start.js');
app.get('/', app.routes.dealer.index);
And my config/routes/index.js is:
var fs = require('fs' ),
required_files = [];
module.exports = function(app){
fs.readdirSync(__dirname).forEach(function(file) {
if (file == "index.js") return;
var name = file.substr(0, file.indexOf('.'));
require('./' + name)(app);
});
}
And it fails to read my route files with this error:
[deb0rian#localhost www.bkbot.org]$ node ./app/dealer.js 3003
info - socket.io started
path.js:299
return splitPathRe.exec(filename).slice(1);
^
RangeError: Maximum call stack size exceeded
Is there something wrong with my file structure?
I want to be able to read only routes in /config/routers/dealer if I run that particular instance, no problem giving it command line argument, but i have to overcome this issue first and I don't know how to read only specific routes subdirectory.
Any help or advise will be appreciated!
Thanks