Run Javascript function in background of NodeJS server - javascript

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()
})

Related

send data from db with and api build with express-generator code 200 no data

my database in mongoDb is connected to my nodeJS i can read it there my nodeJs api is connected to my client-side (in reactJS) and i can send data from my nodeJs api using express-generator to my client-side and is working but when i tried to send my mongoDb database to the client-side is not working( but i'm still getting status 200 but my array is not here . I can't figure out why? i cant see the db when i call the api in postman so i assume the error is in the server-side . If i had a consol.log i can see the db but when i use return it is not working and i cant see the data in postman
here my nodeJs code:
var mongodb = require('mongodb')
var MongoClient = mongodb.MongoClient
var connectionURL = 'mongodb://127.0.0.1:27017'
var databaseName = 'projet_Ecommerce';
const dataFromDb = () => {
MongoClient.connect(connectionURL, {
useNewUrlParser: true
}, (error, client) => {
if (error) {
return console.log('Unable to connect to database')
}
console.log('Connected correctly !');
var db = client.db(databaseName)
db.collection('product').find().toArray(function(error, data) {
if (error) {
return console.log('Unable to find the user')
}
return (data);
})
// Pointer - go to doc
// db.collection('tasks').find({completed: false}).toArray()
})
};
module.exports = dataFromDb
routres / index.js:
var express = require('express');
var router = express.Router();
const bodyParser = require('body-parser')
var dataC = require('../public/javascripts/dataFromDb')
// data = JSON.stringify(data);
// console.log(dataFromDb())
/* GET home page. */
router.get('/', function(req, res, next) {
//console.log(dataFromDb())
res.send(dataC())
});
//console.log(dataFromDb())
module.exports = router;
app.js:
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var cors = require("cors")
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var testAPIRouter = require("./routes/testAPI");
var app = express();
var bodyParser = require("body-parser")
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(cors());
app.use(logger('dev'));
app.use(express.json());
// app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.urlencoded({
extended: false
}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use("/testAPI", testAPIRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// 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;
other files no change

I am getting an error "indexRouter is not defined"

I am getting an error "indexRouter is not defined while I am trying to execute the following code. I tried removing the line but again there are other errors. Can anyone tell me why we are using this common variable router for both index.js and user.js?
This is my app.js
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var bodyParser = require('body-parser');
var index = require('./routes/index');
var users = require('./routes/users');
var dishRouter = require('./routes/dishRouter');
const mongoose = require('mongoose');
mongoose.Promise = require('bluebird');
const Dishes = require('./models/dishes');
const url = 'mongodb://localhost:27017/conFusion';
const connect = mongoose.connect(url,{
useMongoClient : true
});
connect.then((db) => {
console.log('Connected correctly to the server');
},(err) => {console.log(err);});
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/index',indexRouter);
app.use('/users',usersRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// 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;
This is my index.js
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;
This is my users.js
var express = require('express');
var router = express.Router();
/* GET users listing. */
router.get('/', function(req, res, next) {
res.send('respond with a resource');
});
module.exports = router;
You are using wrong variable.
var index = require('./routes/index');
var users = require('./routes/users');
app.use('/index',indexRouter); // it would be index
app.use('/users',usersRouter); // it would be users
Change from indexRouter to index and userRouter to users.

Req has no body when posting with Postman

I'm learning about REST with node.
I'm trying to use post to add an element to my db.
My code:
var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
var AdModule = require('../models/ad');
router.route('/')
.get((req, res) => {
AdModule.find((err, col) => {
if (err)
res.send(err);
res.json(col);
})
})
.post((req, res) => {
var ad = new AdModule();
ad.title = req.body.title;
ad.desc = req.body.desc;
ad.price = req.body.price;
ad.save(err => {
if (err)
res.send('err' + err);
res.json({msg: 'Created'});
})
res.json(req);
});
module.exports = router;
When using post I get req.body is undefined.
My server.js code:
'use strict';
//======================= Base setup =======================\\
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 mongoose = require('mongoose');
var config = require('./globals/config');
var index = require('./routes/index');
var users = require('./routes/users');
var ads = require('./routes/ads');
var app = express();
//========================= DB =============================\\
mongoose.connect(config.db, () => {
console.log('Connected');
});
//========================= Routes =========================\\
app.use('/', index);
app.use('/users', users);
app.use('/ads', ads);
//========================= Parsers ========================\\
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
// app.engine('html', require('ejs').renderFile);
// app.set('view engine', 'html');
//========================= 404 ============================\\
// 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;
So I am using body parser.
This is how I'm posting with postman:
What can be the reason for this madness?
I'm guessing it's something with server.js but have no idea what.
I was following this tutorial.
https://scotch.io/tutorials/build-a-restful-api-using-node-and-express-4#creating-routes-for-a-single-item
Express middlewares executed by order that they are defined, in your case bodyParser defined after ads middleware, just move asd to the bottom
Put your parsers above your routes -- as it happens now, requests are hitting the routes before they have a chance to go through the parsers.

Connecting to MySql in app.js

I am writing a new app, and one of the requirements is that I use the "straight" express boilerplate that include bin/www and an app.js.
I normally just merge the two of them for convenience. Now that I can't, I am wondering...
How can I connect to a DB (which is an async operation) from app.js?
What follows is the full app.js. This does NOT work, because as soon as this line happens:
var connection = await mysql.createConnectionP({
The anonymous function returns an unresolved promise. So the assigned "app" is incomplete, since the code to set it effectively hasn't yet run.
What is the best practice to connect asynchronously to a database keeping the app.js/www duo?
I could connect to the database in www, but then I would need to somehow pass the DB value back to app.js -- is that essentially the only way?
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 promisify = require('util').promisify
var index = require('./routes/index')
var users = require('./routes/users')
var app = express()
var prpl = require('prpl-server')
var jsonreststores = require('jsonreststores')
var mysql = require('mysql')
mysql.createConnectionP = promisify(mysql.createConnection)
console.log("1")
;(async () => {
var connection = await mysql.createConnectionP({
host: 'localhost',
user: 'root',
password: 'ppp',
database: 'sasit'
})
connection.connectP = promisify(connection.connect)
connection.queryP = promisify(connection.query)
connection.endP = promisify(connection.end)
await connection.connectP()
var res = await connection.queryP('SELECT 1 + 1 AS solution')
console.log('The solution is: ', res[0].solution)
await connection.end()
// view engine setup
app.set('views', path.join(__dirname, 'views'))
app.set('view engine', 'jade')
// 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.get('/*', prpl.makeHandler('./public/build', {
builds: [
{name: 'es6-unbundled', browserCapabilities: ['es2015', 'push']},
{name: 'es6-bundled', browserCapabilities: ['es2015']},
{name: 'es5-bundled'}
]
}))
// 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

Node js not returning proper result?

I have this node js program which should return asked variable in the console but it is returning undefined here is code and the input i have trying to parse :-
router.post('/createorder',function(req,res){
console.log(req.body.ProductName);
// var obj=JSON.parse(req.body);
res.send(req.body);
});
the input :
{
"ProductName":"Wine",
"ProductPrice":"500",
"ProductQuantity":"2",
"ProductCost":"1000",
"SellerId":"2"
}
and here is the main module i'm using
var express= require('express');
var routes=require('./routes/api');
var bodyparser=require('body-parser');
var mysql = require('mysql');
var db=mysql.createConnection({
host:'localhost',
user:'root',
password:'',
database:'nodemysql'
})
//setting up express
var app = express();
app.use(bodyparser.urlencoded({extended:false}));
app.use(bodyparser.json());
app.use(routes);
//listen for requests
/*app.get('/',function(req,res){
console.log('get trial method called');
res.send({name:'Atul'});
});*/
app.listen(3000,function(){
console.log('server started on port 3000 ');
});
i want to acess an specific object in order to store in the database?
As soueuls mentioned in the comments, you need to make sure express can parse the body of the request as it doesn't do this by default. Assuming you are using express framework. You could have something like this.
var express = require('express')
var bodyParser = require('body-parser')
var app = express()
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())
Now you can read the body.
notice if you console log your req object before you add in the code above, you will not see the body property.
UPDATE
this is what i have in my app.js file
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 index = require('./routes/index');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// 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);
// 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;
In my routes/index.js i have the following
var express = require('express');
var router = express.Router();
router.post('/createorder',function(req,res){
console.log(req.body);
// var obj=JSON.parse(req.body);
res.send(req.body);
});
module.exports = router;
i tested this with postman app and it works.

Categories