how can i get real time value in node-js? - javascript

I wrote the code to receive data from the device using serial communication device with window.
I can see the data in Console window in eclipse and save data in txt file.
I want to see real-time value and know when did which value was sent
How can I get real time value? Let me know How to write code.
Below is my code:
/**
* 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('save.txt',converted_data + '\r\n',function(err) {
if(err)
console.log(err);
else
console.log('data>txt');
});
});
port.write("mon 1\n", function(){
console.log('write to device');
});
app.get('/data', function (req,res) {
res.redirect('http://localhost:3000/data.html');
});

To see the "real" time in node js, you could use new Date() to get the date it will return something like that:
2017-12-14T09:00:34.359Z
And because it's a Date object, there are all the methods that you can find on MDN.
Or, if you want the exact time using timezone etc..., use the Google Maps timezone API

Related

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');

node.js TypeError: Object has no method get

I'm trying to separate server initiation and other calls from the core file(app.js) but when I try to run it, it issues me error that
http.createServer(app).listen(app.get('port'), function(){
^
TypeError: Object function (){ all code from app.js file }
has no method 'get'
This is app.js file.
/**
* Module dependencies.
*/
module.exports = function(){
var express = require('express');
var routes = require('./routes');
var path = require('path');
var app = express();
// all environments
app.set('port', process.env.PORT || 4000);
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);
return app;
};
and this is server.js file.
var http = require('http'),
app = require('./app');
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
using express#3.4.0
what am I missing OR doing wrong.. please help.
You have no reason to return a function into your app.js file, just return the express object:
var express = require('express');
var app = express();
// ... more variables
// ... the rest of your code
module.exports = app;
Then, the rest of your code into server.js will work fine.
Remember that module.exports works like a "return" into CommonJS (and therefore NodeJS).
See documentation.
You're passing a function to module.exports, so when you require('./app'), you need to call it like a function:
var http = require('http'),
app = require('./app')();
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});

How can I mount MVC nodejs + express

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;

Using Socket.io with Node.js, Express and Jade

I have some trouble to use Socket.io even just to test if a client is connected. I've tried many things and I think that my mistake is, maybe, when I do the app.get function. I have also tried to do this in an route js file but it wasn't conclusive neither. So here are my different codes :
App.js
/**
* Module dependencies.
*/
var express = require('express');
var routes = require('./routes');
var user = require('./routes/user');
var http = require('http');
var path = require('path');
var mongo = require('mongodb');
var monk = require('monk');
var db = monk('mongodb://xxxxx:xxxxx#ds051067.mongolab.com:51067/jdo');
var app = express(),
server = http.createServer(app) ,
io = require('socket.io').listen(server);
// 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.urlencoded());
app.use(express.methodOverride());
app.use(express.cookieParser('This is secret'));
app.use(express.session());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
// development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
io.sockets.on('connection', function (socket) {
console.log('Un client est connecté !');
});
// app.get('/', routes.index);
app.get('/users', user.list);
app.get('/deplacement',routes.deplacement);
app.get('/monCompte', routes.compte);
app.get('/connexion', routes.connexion);
app.get('/', function(req, res) {
res.render('index.jade');
});
server.listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
Index.jade
extends layout
block content
script(src="/socket.io/socket.io.js").
var socket = io.connect('http://localhost:3000');
});
PS : Sorry if my english is bad ^^
You can't use inline javascript in the same script tag as an included script.
extends layout
block content
script(src="/socket.io/socket.io.js")
script.
var socket = io.connect('http://localhost:3000');

app..get() does not seem to work in the Node.js Express application

Here is the app.js file:
var express = require('express'),
routes = require('./routes'),
api = require('./routes/api.js'),
http = require('http'),
path = require('path');
var app= module.exports = express();
/**
* Configuration
*/
// all environments
app.set('port', process.env.PORT || 3001);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.static(path.join(__dirname, 'public')));
app.use(app.router);
// development only
if (app.get('env') === 'development') {
app.use(express.errorHandler());
}
// production only
if (app.get('env') === 'production') {
// TODO
};
/**
* Routes
*/
// serve index and view partials
app.get('/', routes.index);
// redirect all others to the index (HTML5 history)
app.get('*', routes.index);
api(app);
/**
* Start Server
*/
http.createServer(app).listen(app.get('port'), function () {
console.log('Express server listening on port ' + app.get('port'));
});
Here is the routes/api.js file:
var queryObj = {
retrieve:{
api_path:'/api/test/list',
var_name:''
}
};
// All supporting functions used below are defined here !
module.exports = function(app) {
_.each(queryObj, function(obj) {
console.log("Check point 1");
var args = [obj.api_path, function(req, res){
var search_term = obj.var_name ? req.params[obj.var_name] : '';
get(search_term,res);
}];
console.log("Check point 2");
console.log("args:" + args);
app.get.apply(app,args);
});
};
Here is the routes/index.js file:
/*
* GET home page.
*/
exports.index = function(req, res){
console.log("Default view");
res.render('index');
};
So when i run this application and type localhost:3001/api/test/list in the browser, i get follwing output on the console:
Check point 1
Check point 2
`args: args:/api/alarms/list,function (req, res){
var search_term = obj.var_name ? req.params[obj.var_name] : '';
get(search_term,res);
}`
Express server listening on port 3001
Default view
My question is: why is app.get.apply() not working? Instead the default route configured in app.js is taken up!
I think you need to change the order of your route definitions: from most specific (in this case api/test/list to less specific *:
// defined api
api(app);
// serve index and view partials
app.get('/', routes.index);
// redirect all others to the index (HTML5 history)
app.get('*', routes.index);

Categories