NodeJS multiple instances and require routes in subfolder - javascript

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

Related

NodeJS and express, ENOENT on view file

I've got a weird trouble with my nodeJS app since I refactored it.
The app starts well, API answers correctly but when I try to go to /, I get this error : Error: ENOENT, stat '/views/index.html' in my browser.
I now use this folder tree :
project
front
views
index.html
bower_components
app
node
server.js
And here is the content of my server.js file :
var express = require('express');
var app = express();
var morgan = require('morgan');
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
var server = require('http').Server(app);
var io = require('socket.io')(server);
var fs = require('fs');
var nconf = require('nconf');
app.use(express.static(__dirname + '/../front'));
app.use(express.static(__dirname + '/../node_modules'));
app.use(express.static(__dirname + '/../bower_components'));
app.use(morgan('dev'));
app.use(bodyParser.urlencoded({'extended': 'true'}));
app.use(bodyParser.json());
app.use(bodyParser.json({type: 'application/vnd.api+json'}));
app.use(methodOverride());
server.listen(8081);
(...) // some code to define API routes
app.get('/', function (req, res) {
res.sendfile('/views/index.html');
});
I tried to comment app.use(express.static(__dirname + '/../front')); and to call the view using '/front/views/index.html' but the result is the same.
ENOENT means Error NO ENTry which ultimately means it's not able to find your file.
int ENOENT
No such file or directory. This is a "file doesn't exist"
error for ordinary files that are referenced in contexts where they
are expected to already exist.
Your server is attempting to send a file from the root directory of your machine (/views/index.html). You'll probably need to adjust this to fit your file structure.
app.get('/', function (req, res) {
res.sendfile(__dirname + '/../font/views/index.html');
});
I believe you missed to set your views folder.
app.set('views', 'MY_DIR_PATH');
As #Sean3z suggested, I tried to change my sendfile declaration and got another error (Forbidden, sendStream error).
Finally I managed to make it work by changing my static files definition :
app.use('/front', express.static(__dirname + '/../front'));
And by modifying the sendFile : res.sendfile('front/views/index.html');
Strangely, nodeJS understands (but not me :) ) and call the right file at the right place. I just need to correct my calls in the differents file to be ok.
Thanks for the answers.

Error while running app.js in node

I am completely new to node and trying to work with webRTC application.
I have installed node,express and socket.io in my project, However when I try to run app.js I get error. I am unable to debug because I am not experienced enough to spot the error.
The following is the code in app.js
var express = require('express')
, routes = require('./routes')
, http = require('http');
var app = express();
var server = app.listen(3000);
var io = require('socket.io').listen(server); // this tells socket.io to use our express server
app.configure(function(){
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.static(__dirname + '/public'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
});
app.configure('development', function(){
app.use(express.errorHandler());
});
app.get('/', routes.index);
console.log("Express server listening on port 3000");
When I write the command node app.js it shows the following error.
I have setup exprees in my project.
The file structure inside webRTC directory is as follows
Here is the link to webpage that accompanies step by step to setup node,npm express and socket.io inside a peoject . I have followed every step properly but the part where it says to run app.js after downloading socket.io it shows error.
How to install node in ubuntu
Here is the index.js code inside route folder where the error is occuring
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
module.exports = router;
and here is the image which was previously not visible properly

Express 500 TypeError: Cannot read property 'image' of undefined

I'm trying to upload an image file using the Express NodeJS framework but it keeps throwing this error:
Express
500 TypeError: Cannot read property 'image' of undefined
Here's my app.js:
var express = require('express');
var routes = require('./routes');
var uploads = require('./routes/uploads');
var http = require('http');
var path = require('path');
var app = express();
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.bodyParser());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(express.static(path.join(__dirname, 'public')));
app.use(app.router);
// development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
app.get('/', routes.index);
app.post('/uploads', uploads.uploads);
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
Here's upload.js:
var fs = require("fs");
exports.uploads = function(req, res){
//console.log(req.files);
fs.readFile(req.files.image.path, function (err, data) {
console.log("Request handler upload was called");
var imageName = req.files.image.name;
console.log(imageName);
if(!imageName){
console.log("There was an error")
res.redirect("/");
res.end();
} else {
var newPath = __dirname + "/uploads/" + imageName;
fs.writeFile(newPath, data, function (err) {
res.redirect("/uploads/" + imageName);
});
}
});
}
I've tried the other answers on similar questions including using the bodyParser() function and setting the name parameter of input tag as 'image' in my index.jade.
Is there any other solution possible?
Two things came to my mind:
have you checked you have writing rights into "/uploads/"?
check that index.jade -- having two forms on the same page is a sure sign of trouble. There are cases where multiple forms are needed on the same page, but I'm pretty
sure they have no business to do in a simple application. This is most likely the reason your browser makes requests with the wrong parameters. You can also spy on the browser using the Chrome Inspector / Firebug, check if the browser does indeed send the wrong parameters.
Should none of the above help you, please see if you can modify this gist https://gist.github.com/bogdanbiv/eec255655c5aca8ae2de to get similar to your use case. It does not work right now because I do not know what to put inside the index module -- require('./index');
Please note that gist does not allow creating folders. I know it's a security nightmare to have the server code in the same folder as the upload folder, but it's just for debugging purposes.
I just had this issue, and if you look at the logs, the bodyParser() is being deprecated.
https://github.com/senchalabs/connect/wiki/Connect-3.0
They list couple of middleware to use instead. I revised to use "busboy" and it works fine now.
There are examples in the repo
https://github.com/mscdex/busboy
You can redirect the user like this:
res.redirect('/images/' + req.file.filename);
the object file contains:
{ fieldname: 'image',
originalname: 'Final copy.png',
encoding: '7bit',
mimetype: 'image/png',
destination: './public/upload/temp',
filename: 'image-1460839230171',
path: 'public/upload/temp/image-1460839230171',
size: 8441
}

Configuring 'simplest' node.js + socket.IO + Express server

Realized after setting up a simple node.js socket.IO server that it isn't sufficient to handle even the simplest webpages containing script tags.
So I investigating express which is a simple web framework for node.js.
After looking thru the express documentation http://expressjs.com/guide.html
I was still confused as to how I simply combine express with socket.IO on a node.js server.
Couple hours of googling later I came across this tutorial
https://www.digitalocean.com/community/articles/how-to-install-express-a-node-js-framework-and-set-up-socket-io-on-a-vps
/**
* Module dependencies.
*/
var express = require('express')
, routes = require('./routes')
, http = require('http');
var app = express();
var server = app.listen(3000);
var io = require('socket.io').listen(server); // this tells socket.io to use our express server
app.configure(function(){
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.static(__dirname + '/public'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
});
app.configure('development', function(){
app.use(express.errorHandler());
});
app.get('/', routes.index);
console.log("Express server listening on port 3000");
io.sockets.on('connection', function (socket) {
console.log('A new user connected!');
socket.emit('info', { msg: 'The world is round, there is no up or down.' });
});
My question is, would anyone reading this configure their server differently?
I don't need anything special, no session handling etc, just the ability to serve html pages containing links to external CSS and javascript files.
Remove the first app.configure wrapper but leave it's contents. It is useless in general, but especially if you don't pass an argument to it.
Remove methodOverride and bodyParser as you aren't using them
Thanks for all the replies. Finally have something that works and am posting so someone else may benefit. My first attempt(above) was obviously NOT the simplest solution:)
//npm install express
//npm install socket.io
var express = require('express');
var server = express.createServer();
server
.use( server.router )
.use( express.static(__dirname+'/public') )
.get('/api', function(req, res) {
res.write('API');
});
server=server.listen(3000);
var io = require('socket.io');
var socket = io.listen(server);
socket.on('connection', function (client){
// new client is here!
});

Using connect vhost to serve multiple express.js apps

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

Categories