How can I mount MVC nodejs + express - javascript

I have a nodejs + express project. I want to mount controller and view, but I dont know how.
In my app.js I have var stats = require('./controllers/stats'); and app.use(stats);
My folder controllers: stats/index.js and my views: stats/index.jade.
when I try to access localhost:1200/stats --> Cannot GET /stats
Are routes needed?
I use express"3.2.6"
My app.js
/**
* Module dependencies.
*/
var express = require('express')
, routes = require('./routes')
, user = require('./routes/user')
, http = require('http')
, path = require('path');
var app = express();
//modulos
**var stats = require('./controllers/stats');**
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
// development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
app.get('/', routes.index);
app.get('/users', user.list);
//rutas
**app.use(stats);**
var server = app.listen(1200);
console.log('Express server listening on port 1200');
In my controller
var express = require('express');
var app = module.exports = express();
app.set('views', __dirname + '/views');
app.get('/views/stats', function(request, response) {
response.render('index', {
title: 'Estamos en el controlador stats'
});
});
In my view
extends layout
block content
h1= title
p Welcome to #{title}
p esta es la vista del controlador Stats

Here's the complete solution. Since this is a valid question I faced long ago, I give you the whole code. But whether to understand it or not is left to you.
In app.js
var config = require('./config/config.js');
var express = require('express');
var app = express();
config.setConfig(app, express);
if (config.requestMethod == 'HTTPS') {
var request = require('https');
var options = [config.httpsOptions, app];
} else if(config.requestMethod == 'HTTP') {
var request = require('http');
var options = [app];
}
require('./config/db.js');
var server = request.createServer.apply(this, options).listen(app.get('port'), function() {
console.log("Server started");
});
require('./route/router')(app);
In /config/config.js
var fs = require('fs');
module.exports = {
port: 8443,
mode: 'development',
requestMethod: 'HTTP',
httpsOptions: {
key: fs.readFileSync('/etc/apache2/ssl/server.key'),
cert: fs.readFileSync('/etc/apache2/ssl/server.crt'),
requestCert: false,
rejectUnauthorized: false
},
setConfig: function(app, express) {
app.set('port', process.env.PORT || module.exports.port);
app.set('view engine', 'jade');
app.use(express.favicon());
//app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(app.router);
}
};
If it is HTTP only, you can remove HTTPS related options.
in /config/db.js
var mongo = require('mongoskin');
var MONGODB_HOST = "localhost";
var MONGODB_PORT = "27017";
var MONGODB_DATABSE = "dbname";
var MONGODB_USER_RW_NAME = "dbuser";
var MONGODB_USER_RW_PASS = "admin";
var db = mongo.db('mongodb://'+MONGODB_USER_RW_NAME+':'+MONGODB_USER_RW_PASS+'#'+MONGODB_HOST+':'+MONGODB_PORT+'/'+MONGODB_DATABSE, {safe: false});
var Tracking = require('../model/tracking.js');
GLOBAL.db = db;
GLOBAL.HOST = 'localhost';
GLOBAL.HEADER_MATCH = /localhost/i;
GLOBAL.ROOT_PATH = '/site/index.php/';
GLOBAL.Tracking = Tracking.construct(db);
Tracking is a custom model I wrote. You will see the code later.
In /route/router.js
router = function(app) {
var routes = {
'POST /test/link': 'testController.test'
};
var loadedControllers = {};
for(var i in routes) {
var requestMethod = i.split(' ')[0].toLowerCase();
var routeURL = i.split(' ')[1];
var controller = routes[i].split('.')[0];
var method = routes[i].split('.')[1];
if (loadedControllers[controller]) {
var loadControl = loadedControllers[controller];
} else {
var loadControl = require('../controller/' + controller);
loadedControllers[controller] = loadControl;
}
app[requestMethod](routeURL, loadControl[method]);
}
};
module.exports = router;
As and when you add a new URL, or API, you need to add one entry in routes object linking URL to a controller.
In /controller/testController.js,
exports.test = function(req, res) {
//Your code
};
In /model/Tracking/js,
exports.construct = function(db) {
var _Tracking = function(data) {
this.info = {
_id: data && data._id || null,
value: data.value || 0
};
_Tracking.test = function(id, cb) {
//your code involving db
cb(); //Send parameters to callback if necessary
//Call this function from controller directly using Tracking.test
};
return _Tracking;
};
That's it. You can build on top of this.

First of all I need three folders in the root of my app.
models
views
controllers
Now on to the app.js
var express = require('express');
,http = require('http');
,path = require('path');
,app = express();
,fs = require('fs');
// database connection
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/mydb');
// some environment variables
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.cookieParser('your secret here'));
app.use(express.session());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
// dynamically include routes (Controller)
fs.readdirSync('./controllers').forEach(function (file) {
if(file.substr(-3) == '.js') {
route = require('./controllers/' + file);
route.controller(app);
}
});
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
Here is an example that I place in controllers/users.js
var mongoose = require('mongoose')
var Video = require('../models/user');
module.exports.controller = function(app) {
/**
* a home page route
*/
app.get('/signup', function(req, res) {
// any logic goes here
res.render('users/signup')
});
/**
* About page route
*/
app.get('/login', function(req, res) {
// any logic goes here
res.render('users/login')
});
}
res.render('users/signup') which results in the view being loaded from views/users/signup.jade in this app.
Finally, for reference, here is what the model in models/user.js may look like:
Var mongoose = require('mongoose')
,Schema = mongoose.Schema
userSchema = new Schema( {
username: String,
password: String
}),
User = mongoose.model('user', userSchema);
module.exports = User;

Related

Problem in rendering ejs template with Express

I am using Node.js together with Express and EJS.
Below is my code:
var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
var app = express();
var urlencodedParser = bodyParser.urlencoded({ extended: false });
var publicPath = path.resolve(__dirname, 'public');
app.use(express.static(publicPath));
//app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.get('/form_get.html', (req, res) => {
res.sendFile(__dirname + "/" + "form_get.html")
})
app.get('/process_get', (req, res) => {
console.log(req.query.first_name);
res.render(path.join(__dirname+'/views/thankyou.ejs'), { name: req.query.first_name});
})
var server = app.listen(3000, () => {
var host = server.address().address;
var port = server.address().port;
console.log(`Example app listening at ${host}:${port}`);
})
My folder structure is below:
mysql (folder)
node_modules (folder)
app4.js (file)
package.json (file)
public (folder, it contains form_get.html)
views (folder, it contains thankyou.ejs)
The problem is the failing to look up thankyou.ejs into the views folder.
I get the following error message:
Error: Failed to lookup view "thankyou.ejs" in views directory
".../mysql/views"
What can be the problem?
When You use app.set('view engine', 'ejs'); It is important to note that res.render() will look in a views folder for the view.
In this case
I mirrored Your project and it works fine with couple tiny changes...
Project Folder and file structure.
app.js
var express = require("express");
var path = require("path");
var bodyParser = require("body-parser");
var app = express();
var urlencodedParser = bodyParser.urlencoded({ extended: false });
var publicPath = path.resolve(__dirname, "public");
app.use(express.static(publicPath));
app.set("view engine", "ejs");
app.get("/form_get", (req, res) => {
res.sendFile(__dirname + "/" + "form_get.html");
});
app.get("/process_get", (req, res) => {
res.render("thankyou");
});
var server = app.listen(3000, () => {
var host = server.address().address;
var port = server.address().port;
console.log(`Example app listening at ${host}:http://localhost:${port}`);
});
Output:
http://localhost:3000/process_get (thankyou.ejs) file.
Output:
http://localhost:3000/form_get (form_get.html) file

how can i get run time in javascript?

I wrote the code to receive data from the device using serial communication device with window.
I can see Continuous data in Console window in eclipse and save data in txt file.
Data transfer continues until the port is disconnected
I want to see time that Data is transmitted .
Finally, I want to get a time-data graph , so Time data is needed
How do I write code? The code below is the code I wrote
/**
* Module dependencies.
*/
var express = require('express')
, routes = require('./routes')
, user = require('./routes/user')
, http = require('http')
, path = require('path');
var app = express();
var SerialPort = require('serialport');
var UrlParser = require('url');
var fs = require('fs');
var readline = require('readline');
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
// development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
app.get('/', routes.index);
app.get('/users', user.list);
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
var port = new SerialPort("COM32" , {
baudRate:9600,
});
port.on("open" , function(){
console.log('open success');
});
port.on('data', function(data) {
converted_data = parseFloat(data);
console.log(converted_data);
fs.appendFile('TestDB.sql',converted_data + '\r\n',function(err) {
if(err)
console.log(err);
else
console.log('data->db');
});
});
port.write("mon 1\n", function(){
console.log('write to device');
});
app.get('/data', function (req,res) {
res.redirect('http://localhost:3000/data.html');

Run Javascript function in background of NodeJS server

I have written a function that periodically checks the battery statuses of connected android devices and returns an array. How can I run this function on server startup and have it continuously running while providing its information to other pages?
var minutes = 1, the_interval = minutes * 60 * 500;
setInterval(function() {
adb.devices().then(function(devices) {
var promises = new Array();
for (var i = 0; i < devices.length; i++){
promises.push(adb.checkBattery(devices[i]));
}
Promise.all(promises).then(function(availableDevices) {
console.log('Updated:');
console.log(availableDevices);
return availableDevices;
});
});
}, the_interval);
This is my app.js file which was automatically created when I opened a new project. I added app.use for the various routes I have created.
var express = require('express');
var path = require('path');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var multer = require('multer');
var adb = require('./adb.js');
var index = require('./routes/index');
var users = require('./routes/users');
var devices = require('./routes/devices');
var openBrowser = require('./routes/openBrowser');
var closeBrowser = require('./routes/closeBrowser');
var openApp = require('./routes/openApp');
var closeApp = require('./routes/closeApp');
var install = require('./routes/install');
var uninstall = require('./routes/uninstall');
var pull = require('./routes/pull');
var push = require('./routes/push');
var battery = require('./routes/battery');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', index);
app.use('/users', users);
app.use('/devices', devices);
app.use('/openBrowser', openBrowser);
app.use('/openApp', openApp);
app.use('/closeApp', closeApp);
app.use('/install', install);
app.use('/closeBrowser', closeBrowser);
app.use('/uninstall', uninstall);
app.use('/pull', pull);
app.use('/push', push);
app.use('/battery', battery);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
using express, if i understand correctly, you should run it in some interval :
var express = require('express');
var app = express();
app.listen(3000, function () {
yourFunction();
setInterval(yourFunction, << period in ms >>);
});
function yourFunction()
{
<< your code >>
}
if u want to use your function reacting on some request to your web server, you better to use middleware :
var express = require('express');
var app = express();
app.use(function(req,res) {
if(condition)
yourFunction();
})
app.listen(3000, function () {
});
function yourFunction()
{
<< your code >>
}
screenshot According to the documentation you can use
server = app.listen(3000, function () {
});
server.on('listening', () => {
your function()
})

Cannot GET /index in nodejs

I have written a server named "app.js" which display many pages of my web site.
var http=require("http");
var express = require('express');
var app = express();
var server = http.createServer(app);
var ejs = require('ejs');
var path = require('path');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
// routes
var route = require('./route');
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
server.listen(3000,function(){
console.log("server listen at localhost:3000");});
app.get('/', route.index);
route.js:
var index = function(req, res, next) {
if(!req.isAuthenticated()) {
res.redirect('/index');
} else {
var user = req.user;
if(user !== undefined) {
user = user.toJSON();
}
res.render('menu', {title: 'Home', user: user});
}
};
module.exports.index = index;
The folder of project:
/interface
/views
index.ejs
app.js
route.js
How can I fix it ? what is the mistake in my program?
Your app.get is unreachable after server.listen.
Place it before:
app.js:
var http=require("http");
var express = require('express');
var app = express();
var server = http.createServer(app);
var ejs = require('ejs');
var path = require('path');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
// routes
var route = require('./route');
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// here:
app.get('/', route.index);
server.listen(3000,function(){
console.log("server listen at localhost:3000");});
// app.get('/', route.index); <= not here
When not authenticated, redirection is not what you want, but:
route.js:
// res.redirect('/index');
res.render('index');

while Integrating nodejs -mysql module file into app.use getting an error file notfound error404

I created a nodejs-mysql file .
when i give listen(8084) port number and test on browser it displays data .
when i integrate into main folder app.use('/', salonsce_fournisseur) which use default 3000 port and without 8084 number .
it is showing an error 404 file not found.
some body please explain to me where i am doing mistake.
here is the code
var express = require('express');
var app = express();
var router = express.Router();
var http = require('http');
var mysql = require('mysql');
var url = require('url');
var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
database: 'test'
});
var fournisseurJoinsQuery = 'SELECT * FROM `salonsce_fournisseurs`;
console.log('MySQL Connection details '+connection);
http.createServer(function (req, res)
{
var url_parts = url.parse(req.url, true);
var query1 = url_parts.query;
console.lop('kkkkkkkkkkkkkkkkk')
console.log(query1);
console.log('Creating the http server');
connection.query(fournisseurJoinsQuery , function(err, rows, fields)
{
console.log('Connection result error '+err);
console.log('no of records is '+rows.length);
res.writeHead(200, { 'Content-Type': 'application/json'});
res.end(JSON.stringify({"success":1,"count":rows.length,"results":rows}));
res.end();
});
});
module.exports = router;
my app.js code is:
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
//var mysql = require('mysql');
var routes = require('./routes/index');
var users = require('./routes/users');
var files = require('./routes/files');
var salonsce_photos = require('./routes/salonsce.photos');
var salonsce_fournisseur = require('./routes/salonsce.fournisseur');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use('/', routes);
app.use('/users', users);
app.use('/salonsce.photos', salonsce_photos);
app.use('/salonsce.fournisseur', salonsce_fournisseur);
});
module.exports = app;
if i type on url : localhost:3000/salonsce.fournisseur it should display the data.
Thanks in advance.

Categories