inside a multidimensional array, created by a mysql query, I have saved the connection parameters to multiple opcua machines.
I believe the problem is the async functions inside the loop, but I don't know how to fix it.
When I run the script, no sessions are started and this error is returned
myprj/node-opcua-assert/dist/index.js:11
const err = new Error(message);
^
Error
at assert (myprj/node-opcua-assert/dist/index.js:11:21)
at OPCUAClientImpl._createSession (myprj/node-opcua-client/dist/private/opcua_client_impl.js:856:40)
at OPCUAClientImpl.createSession (myprj/node-opcua-client/dist/private/opcua_client_impl.js:273:14)
at OPCUAClientImpl.createSession (myprj/thenify/index.js:65:46)
at OPCUAClientImpl.createSession (myprj/node-opcua-client/dist/private/opcua_client_impl.js:267:25)
at myprj/thenify/index.js:72:10
at new Promise (<anonymous>)
at OPCUAClientImpl.createSession (myprj/thenify/index.js:70:12)
at myprj/read_node.js:8
The code is:
/*
Here is the code not listed for import settings and settings connection database
*/
const endpointUrl = config.endpointUrl;
const opcua = require("node-opcua");
const ping = require('ping');
const {
AttributeIds,
OPCUAClient
} = require("node-opcua");
const chalk = require("chalk");
const mysql = require('mysql2');
/*receive arguments*/
var argvs = process.argv.slice(2);
var args = [];
argvs.forEach(function (val, index, array) {
var arg = val.split('=');
args[arg[0]] = arg[1];
});
/*
Db connection
*/
var con = mysql.createConnection(config.mysql);
con.connect(function(err) {
if (err) throw err;
console.log(chalk.green("DB Connected!"));
});
/*
Reading machine->recipes->nodes
*/
;(async () => {
try {
var sql = "";
sql = "SELECT * FROM machine ...";
con.query(sql, function(err, machines) {
if (err) throw err;
/*
Machine list
*/
var m = 0;
machines.forEach(async machine => {
/*
Check if machine is alive
*/
let HostInfo = await ping.promise.probe(machine.ip);
console.log(HostInfo.alive);
if(HostInfo.alive)
{
console.log('Host ' + machine.ip + ' raggiungibile!');
var endpointUrl = machine.ip + ':' + machine.port;
console.log(endpointUrl);
client = OPCUAClient.create({
endpointMustExist: false,
});
console.log(" connecting to ", chalk.cyan(endpointUrl));
await client.connect(endpointUrl);
console.log(" connected to ", chalk.green(endpointUrl));
session = await client.createSession();
console.log(" session created".yellow);
var sql = "";
sql = "SELECT * FROM machine_recipes...";
/*
Machine recipes
*/
con.query(sql, function(err, machine_recipes) {
if (err) throw err;
machine_recipes.forEach(async machine_recipe => {
/*
Machine recipes NODES to check
*/
var sql = "";
sql = "SELECT * FROM machine_recipes_nodes...";
con.query(sql, function(err, nodes) {
var i = 0;
nodes.forEach(async node => {
var params = JSON.parse(node.params);
var dataValues = await session.read([{
nodeId: params.unitid
}]);
var node = params.unitid;
var value = dataValues [0].value.value;
/*
Saving value in database...
*/
});
});
});
});
}
m++;
});
});
} catch (err) {
console.log('error !', err.message);
}
})();
Thanks for help
Related
I write a node script module for using in different pages of my application. this script named "parsDbsPostgres.js". then i write a script for calling and using from "parsDbsPostgres.js", this script named "pg.js". the content of this two file is :
// parsDbsPostgres.js
var pg = require('pg');
var pool;
var config = {
host: 'localhost',
port: 5432,
user: 'postgres',
password: '123321',
database: 'trading',
max: 20,
idleTimeoutMillis: 10000,
connectionTimeoutMillis: 2000,
}
function getPool(){
if (pool){ return pool; } // if it is already there, grab it here
pool = new pg.Pool(config);
return pool;
}
function doPgQuery(inputArguments={}, callbackFunction){
// console.log(inputArguments);
var outputArguments = {};
if (Object.prototype.toString.call(inputArguments)!='[object Object]'){
outputArguments['viReturn'] = false;
outputArguments['viResult'] = 'INPUT_ARGUMENT_NOT_OBJECT';
callbackFunction(outputArguments);
}
if ('mtPool' in inputArguments) { mtPool = inputArguments['mtPool']; }
if ('mtSqlQuery' in inputArguments) { mtSqlQuery = inputArguments['mtSqlQuery']; }
try {
mtPool.connect(function(err, client, done){
if(err){
print(err);
// done(); // releases connection back to the mtPool
// print(err);
outputArguments['viCode'] = 1121;
outputArguments['viReturn'] = false;
outputArguments['viMessage'] = 'ERROR_POOL_CONNECT';
outputArguments['viResult'] = err;
callbackFunction(outputArguments);
}
// if(inputArguments.hasOwnProperty('mtSqlQuery')){
if(mtSqlQuery){
client.query(inputArguments.mtSqlQuery, function(err, result){
if(err){
done();
// print(err);
outputArguments['viCode'] = 1122;
outputArguments['viMessage'] = 'ERROR_CLIENT_QUERY';
outputArguments['viSql'] = inputArguments.mtSqlQuery;
outputArguments['viReturn'] = false;
outputArguments['viResult'] = err;
callbackFunction(outputArguments);
}else{
// var lastInsertID = result.rows[0].id;
done();
// print(result);
outputArguments['viCode'] = 1123;
outputArguments['viSql'] = inputArguments.mtSqlQuery;
outputArguments['viReturn'] = true;
outputArguments['viResult'] = result.rows;
// console.log(outputArguments);
// console.log(inputArguments.mtSqlQuery);
// console.log(mtSqlQuery);
// console.log('-------------------------------------------------------------------------------------------------------------\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r');
callbackFunction(outputArguments);
}
// print('Client will end now!!!');
// client.end();
});
}else{
done();
outputArguments['viCode'] = 1124;
outputArguments['viMessage'] = 'ERROR_HASOWN_PROPERTY_QUERY';
outputArguments['viReturn'] = false;
outputArguments['viResult'] = err;
callbackFunction(outputArguments);
}
});
}catch(e){
// return {stat:0 , error : e } ;
console.log(e);
}
};
module.exports = {
getPool,
doPgQuery,
}
// pages.js
var parsDbsPostgres = require('./parsDbsPostgres.js');
const process = require('process');
process.on('beforeExit', (code) => {
console.log('Process beforeExit event with code: ', code);
});
var start = Date.now();
var counter = 10000000000;
var arrErrors = [];
var nErrors = 0;
function loopCallbackInsert(){
// var mySqlQuery = 'SELECT id FROM binance_signals WHERE id = 1 ORDER BY id DESC LIMIT 1';
var mySqlQueryINSERT = 'INSERT INTO binance_signals (id) VALUES(DEFAULT) RETURNING id';
var ellipsed = (Date.now())-start;
var newEllipsed = '000000000000'+ellipsed;
newEllipsed = newEllipsed.substr(newEllipsed.length - 10);
insertInsertArguments = {
mtPool: parsDbsPostgres.getPool(),
mtFieldType: 'float',
mtSqlQuery: mySqlQueryINSERT,
}
parsDbsPostgres.doPgQuery(insertInsertArguments, function(callbackInsertFunction){
counter++;
if(!callbackInsertFunction.viReturn){
nErrors++;
arrErrors.push(callbackInsertFunction);
}
console.log('loopCallbackInsert', nErrors, arrErrors, counter, callbackInsertFunction.viResult);
});
}
function loopCallbackSelect(){
var mySqlQuerySelect = 'SELECT id,symbol FROM binance_signals ORDER BY id DESC LIMIT 1';
// var mySqlQuery = 'INSERT INTO binance_signals (id) VALUES(DEFAULT) RETURNING id';
var ellipsed = (Date.now())-start;
var newEllipsed = '000000000000'+ellipsed;
newEllipsed = newEllipsed.substr(newEllipsed.length - 10);
insertSelectArguments = {
mtPool: parsDbsPostgres.getPool(),
mtFieldType: 'float',
mtSqlQuery: mySqlQuerySelect,
}
parsDbsPostgres.doPgQuery(insertSelectArguments, function(callbackSelectFunction){
counter++;
if(!callbackSelectFunction.viReturn){
nErrors++;
arrErrors.push(callbackSelectFunction);
}
console.log(' loopCallbackSelect', nErrors, arrErrors, counter, callbackSelectFunction.viResult);
});
}
process.on('exit', (code) => {
console.log('----------------------- Process exit event with code: ', code, nErrors, arrErrors, '-------------------------------');
});
try {
var schedule = require('node-schedule');
var s = schedule.scheduleJob('* * * * * *', function () { // every 1 second
for (i = 0; i < 1000; i++){
loopCallbackSelect();
loopCallbackInsert();
}
});
}catch(e){
// return {stat:0 , error : e } ;
console.log(e);
}
unfortunately sometimes i get error "Error: timeout exceeded when trying to connect". how i can solve this error in this two script.
thanks
I have a mongoDB which contains the time where in my durable function should run (e.g. 8:00, 9:01, 10:20). Now I have my Orchestrator code below, nothing works inside the mongoClient.connect. Why???
const df = require("durable-functions");
const moment = require("moment");
const mongoClient = require("mongodb").MongoClient;
module.exports = df.orchestrator(function*(context) {
context.log("Getting time schedules in DB");
var timeSched = [];
var dbName = <dbName>;
var collectionName = <collectionName>;
var query = {id: "1"};
try{
mongoClient.connect(<mongoDB_connection_string>,{useNewUrlParser: true, authSource: dbName}, function (err, client) {
//Anything inside this does not log or work
if(err){
context.log(`Error occurred while connecting to DB ${err}`)
return context.done();
}else{
context.log('MongoClient connected to DB');
}
var collection = client.db(dbName).collection(collectionName);
collection.find(query).toArray(function(err, result) {
if (err) throw err;
for(let i = 0; i < result.length; i++){
timeSched.push(result[i].time); //e.g.8:00
}
client.close();
//This should log [8:00,9:01,10:01] but it does not log
context.log(timeSched);
context.done();
});
});
//This logs 0
context.log(timeSched.length);
for (let j = 0; j < timeSched.length; j++) {
const deadline = moment.utc(context.df.currentUtcDateTime).add(3, 'minutes');
yield context.df.createTimer(deadline.toDate());
yield context.df.callActivity("ActivityFunction",timeSched[j]);
}
context.done();
}catch(e){
context.log(`Error ${e}`);
context.done();
}
});
Try the code below to check if you can connect to DB first. Use console.log instead of context.log.
const df = require("durable-functions");
const mongoClient = require("mongodb").MongoClient;
module.exports = df.orchestrator(function*(context) {
var mongoClient = require("mongodb").MongoClient;
mongoClient.connect(
"mongodb://tonytest:78jst6Mh****.documents.azure.com:10255/?ssl=true",
function(err, client) {
if (err) {
console.log(`Error occurred while connecting to DB ${err}`);
return context.done();
} else {
console.log("MongoClient connected to DB");
}
client.close();
}
);
});
Try with console.log(timeSched); to output timeSched. Besides, when you execute console.log(timeSched.length);, timeSched hasn't been granted value. That's why you got 0;
am new to nodeJS and am having some problem understanding how async and await works. Here is my code am using to fetch data from my database:
const sql = require('mssql');
const config = require('./config');
var Student = require('./student');
module.exports.getAllStudents = async function getAllStudents(){
var studentArray = new Array();
console.log('dbconnection');
var conn = new sql.ConnectionPool(config.dbConfig[0]);
conn.connect()
.then(()=>{
var req = new sql.Request(conn);
req.query('SELECT * from student').then((recordset)=> {
var dataset = recordset.recordset;
for(var index = 0; index<dataset.length; index++){
var student = new Student(dataset[index].student_id , dataset[index].first_name, dataset[index].last_name, dataset[index].student_address , dataset[index].age);
studentArray.push(student);
}
conn.close();
}).catch( (error) =>{
console.log("An error has occured while executing your query ");
console.log(error);
});
})
.catch( (error)=> {
console.log("An error has occured while trying to connect to the database : ");
console.log(error);
});
return studentArray;
}
and here is the endpoint where i made a call to fetch all the students:
app.get('/getAllStudents' , function(req , res){
var studentArr = new Array();
studentArr = query.getAllStudents();
console.log('====================================');
//console.log(studentArr); //this prints undefined
//console.log('length:======' + studentArr.length);
//var json = JSON.stringify(studentArr);
res.status(200);
res.send('got all students');
})
am trying to understand how to counter this error, what needs to be done to wait for my query to get the results then prints the student array. Could anybody explain to me what needs to be done and why it is not working ?
Because it's asynchronous you should return a promise then resolve() the results
const sql = require('mssql');
const config = require('./config');
var Student = require('./student');
module.exports.getAllStudents = function getAllStudents() {
return new Promise((resolve, reject) => {
var studentArray = new Array();
console.log('dbconnection');
var conn = new sql.ConnectionPool(config.dbConfig[0]);
conn.connect()
.then(()=>{
var req = new sql.Request(conn);
req.query('SELECT * from student').then((recordset)=> {
var dataset = recordset.recordset;
for(var index = 0; index<dataset.length; index++){
var student = new Student(dataset[index].student_id , dataset[index].first_name, dataset[index].last_name, dataset[index].student_address , dataset[index].age);
studentArray.push(student);
}
resolve(studentArray);
conn.close();
}).catch( (error) =>{
console.log("An error has occured while executing your query ");
console.log(error);
reject(error);
});
})
.catch( (error)=> {
console.log("An error has occured while trying to connect to the database : ");
console.log(error);
reject(error);
});
});
}
Then add async to your function and await to query.getAllStudents()
app.get('/getAllStudents' , async function(req , res){
var studentArr = new Array();
studentArr = await query.getAllStudents();
I do have a shell script that invokes
mongo --eval "db.copyDatabase('somedatabase', 'somedatabase_duplicate', 'sourcehost')"
to copy a database.
Currently I am stuck with doing the same from within a Node.JS application. Calling
mongoCommand = `db.copyDatabase("somedatabase", "somedatabase_duplicate", "localhost")`;
db.command(mongoCommand, function(commandErr, data) {
if(!commandErr) {
log.info(data);
} else {
log.error(commandErr.errmsg);
}
});
Always resulsts in a "no such command" error message.
Edit for clarification: Using db.admin().command() results in the same problem and using the command suggested in enter link description here, too.
What's the correct way to call this command or, alternatively, to clone a database from Node.JS?
Well, you are trying to copy database which is administration operation so have to do with admin account. Again, to copy database command is copydb.
try running this command in shell, db.copyDatabase and you'll see source of command.
try:
var assert = require('assert');
var MongoClient = require('mongodb').MongoClient;
var url = 'mongodb://localhost:27017/test';
MongoClient.connect(url, function(err, db) {
if (err) {
console.log(err);
}
else {
var mongoCommand = { copydb: 1, fromhost: "localhost", fromdb: "test", todb: "test_dup" };
var admin = db.admin();
admin.command(mongoCommand, function(commandErr, data) {
if (!commandErr) {
console.log(data);
} else {
console.log(commandErr.errmsg);
}
db.close();
});
}
});
//core modules
const assert = require('assert')
const MongoClient = require('mongodb').MongoClient;
const moment = require('moment');
const mongo = require('mongodb')
//custom modules
let { ip, port, database } = require('./dbUpgradeConfig')
const url = `mongodb://${ip}:${port}`
let todayDate = moment().format('DD/MM/YYYY HH:mm')
console.log(todayDate)
const myDate = new Date()
console.log(myDate)
var d = Date(Date.now());
// Converting the number of millisecond in date string
a = d.toString()
// Options for mongoDB
const mongoOptions = { useNewUrlParser: true }
let db
//TODO: handle reconnect
let connect = () => {
return new Promise((resolve, reject) => {
if (db) resolve()
else {
mongo.connect(url, mongoOptions, (err, client) => {
if (err) reject(err)
else {
db = client.db(database)
resolve()
}
})
}
})
}
/**
* #description create duplicate database from current database in mongodb
*/
let CloneDb = () => {
return new Promise((resolve, reject) => {
connect()
.then(() => {
console.log(db)
let mongoCommand = { copydb: 1, fromhost: "localhost", fromdb: "db_name", todb: "db_name_duplicate" }
let adminDB = db.admin()
adminDB.command(mongoCommand, function (commandErr, data) {
if (!commandErr) {
console.log(data)
} else {
console.log(commandErr.errmsg)
}
});
})
})
}
CloneDb().then(data => {
// debugger;
console.log("The clone db", data)
})
Node JS : my SQL callback function return data to server or broadcast to room id
1] Server.js
var express = require('express');
var app = express();
var http = require('http');
var server = http.createServer(app);
var io = require('socket.io').listen(server, {log:false });
var dbAction = require('./dbAction');
var yql = require('yql');
server.listen(config.port);
app.get('/', function (req, res) {
res.sendfile(__dirname + '/public/index.html');
});
io.sockets.on('connection', function(socket)
{
socket.on('userAuthentication', function(loginDetails){
var test = dbAction.userAuthentication(loginDetails);
console.log(test);
console.log("---------------");
});
});
2] dbAction.js
var mysql = require('mysql');
var userInfo = {};
var connection = "";
exports.userAuthentication = function(info)
{
userInfo.unm = (info.unm).trim();
userInfo.pwd = (info.pwd).trim();
connection = mysql.createConnection({host: "localhost", user: "root", password: ""});
connection.query('USE user');
connection.query("SELECT * FROM users WHERE username ='"+ userInfo.unm +"'", function(err, results)
{
if (err) { console.log(err); }
else if(results.length > 0)
{
var key = (results[0]['key']).trim();
if(key != ""){
var select_sql = "another query";
connection.query(select_sql, function(err, results_1)
{
if (err) { console.log(err); }
else if(results_1.length > 0)
{
console.log( results_1);
}
});
}
}
});
}
Queries:
1] I want "result_1" return to server.js "userAuthentication" in test variable.
2] Otherwise "result_1" broadcast to specific room.
Add the socket as a parameter, then you can use the socket object to emit in a room.
You could also add the io object but i think it's better to give only the socket, if you want to broadcast for example.
server.js
var test = dbAction.userAuthentication(loginDetails,socket);//NEW
dbAction.js
exports.userAuthentication = function(info,socket)//NEW
{
userInfo.unm = (info.unm).trim();
userInfo.pwd = (info.pwd).trim();
connection = mysql.createConnection({host: "localhost", user: "root", password: ""});
connection.query('USE user');
connection.query("SELECT * FROM users WHERE username ='"+ userInfo.unm +"'", function(err, results)
{
if (err) { console.log(err); }
else if(results.length > 0)
{
var key = (results[0]['key']).trim();
if(key != ""){
var select_sql = "another query";
connection.query(select_sql, function(err, results_1)
{
if (err) { console.log(err); }
else if(results_1.length > 0)
{
console.log( results_1);
socket.to(ROOM_ID).emit('result', results_1);//NEW
}
});
}
}
});
}