So I currently have two functions which are called when I add a call to a bridge, and two functions within that get called automatically, so am trying to use JQuery so they only get called when a button is clicked, and then I can work from there in the server side of things.
It may have be an issue with using both ARI client and socket.io together, am not too sure am still learning as am going along.
Issue being at the moment an error gets thrown up saying $ isnt defined.
JQuery does work I have another file am calling which is all JQuery and handles my socket.io client side.
$("#mute").click(function () {
alert("Handler for .click() called.");
channel.mute({
channelId : 111
},
function (err) {});
});
$("#kick").click(function () {
alert("Handler for .click() called.");
channel.hangup({
channelId : 111
},
function (err) {});
});
As anyone any experience using both or even have any suggestion as to how I can do this.
Full code listing;
var ari = require('ari-client');
var util = require('util');
var chanArr = [];
var test;
var mute;
var express = require('express'),
app = express(),
server = require('http').createServer(app),
io = require('socket.io').listen(server);
//ARI client
ari.connect('http://localhost:8088', 'asterisk', 'asterisk', clientLoaded);
function clientLoaded(err, client) {
if (err) {
throw err;
}
// find or create a holding bridges
var bridge = null;
client.bridges.list(function (err, bridges) {
if (err) {
throw err;
}
bridge = bridges.filter(function (candidate) {
return candidate.bridge_type === 'mixing';
})[0];
if (bridge) {
console.log(util.format('Using bridge %s', bridge.id));
} else {
client.bridges.create({
type : 'mixing'
}, function (err, newBridge) {
if (err) {
throw err;
}
bridge = newBridge;
console.log(util.format('Created bridge %s', bridge.id));
});
}
});
// handler for StasisStart event
function stasisStart(event, channel) {
console.log(util.format(
'Channel %s just entered our application, adding it to bridge %s',
channel.name,
bridge.id));
channel.answer(function (err) {
if (err) {
throw err;
}
bridge.addChannel({
channel : channel.id
}, function (err) {
var id = chanArr.push(channel.name)
console.log("Value: " + test);
test = channel.name;
updateSip);
if (err) {
throw err;
}
//If else statement to start music for first user entering channel, music will stop once more than 1 enters the channel.
if (chanArr.length <= 1) {
bridge.startMoh(function (err) {
if (err) {
throw err;
}
});
} else if (chanArr.length === 2) {
bridge.stopMoh(function (err) {
if (err) {
throw err;
}
});
} else {}
});
});
$("#mute").click(function () {
alert("Handler for .click() called.");
channel.mute({
channelId : 111
},
function (err) {});
});
$("#kick").click(function () {
alert("Handler for .click() called.");
channel.hangup({
channelId : 111
},
}
// handler for StasisEnd event
function stasisEnd(event, channel) {
console.log(util.format(
'Channel %s just left our application', channel.name));
console.log(channel.name);
var index = chanArr.indexOf(channel.name);
chanArr.splice(index, 1);
updateSip();
}
client.on('StasisStart', stasisStart);
client.on('StasisEnd', stasisEnd);
client.start('bridge-hold');
}
//Socket.io logic here
server.listen(3009, function () {
console.log('listening on *:3009');
});
app.use(express.static(__dirname + '/public'));
app.get('/', function (req, res) {
res.sendfile(__dirname + "/testPage.html");
});
io.sockets.on('connection', function (data) {
updateSip();
});
io.sockets.on('muting', function (data) {
mute = data;
console.log("client side:" + mute);
});
function updateSip() {
console.log("Value: " + test);
io.sockets.emit('sip', chanArr);
}
The error saying $ isnt defined would be jQuery not being available. If we could see more of the code as its structured on the page, why it is not available would be more clear.
Related
I have the following code which I'm using to learn how to transition from callbacks, through to async, then moving onto promises and finally await.
For the first time, I'm really struggling to understand why I get nothing at all returned to the console.
I have several logging events in place, but these never trigger inside the code, and non of the errors are thrown / exceptions raised.
I have put in additional logging outside the functions to demonstrate that the files running when requesting eg, nodemon app.js from the terminal. However, the terminal hangs on 'starting'.
What am I doing wrong?
In addition to the code here, I have tried extensively wrapping different parts in try / catch blocks, but nothing is ever returned.
index.js:
const mysql = require('mysql');
const async = require('async');
const dbConfig = require('./db');
const employees = require('./employees');
async.series(
[
function(callback) {
mysql.createConnection(dbConfig, function(err) {
callback(err);
});
},
function(callback) {
employees.getEmployee(101, function(err, emp) {
if (err) {
callback(err);
return;
}
console.log(emp);
});
}
],
function(err) {
if (err) {
console.log(err);
}
}
);
employees.js:
const mysql = require('mysql');
const async = require('async');
function getEmployee(empId, getEmployeeCallback) {
async.waterfall(
[
function(callback) {
mysql.createConnection(function(err, conn) {
if (err) {
console.log('Error getting connection', err);
} else {
console.log('Connected to database');
}
callback(err, conn);
});
},
function(conn, callback) {
conn.execute(
`select *
from employees`,
function(err, result) {
if (err) {
console.log('Error executing query', err);
} else {
console.log('Query executed');
}
callback(err, conn, result);
}
);
}
],
function(err, conn, result) {
if (err) {
getEmployeeCallback(err);
} else {
getEmployeeCallback(null, result.rows[0]);
}
// If error getting conn, no need to close.
if (conn) {
conn.close(function(err) {
if (err) {
console.log('Error closing connection', err);
} else {
console.log('Connection closed');
}
});
}
}
);
}
module.exports.getEmployee = getEmployee;
db.js:
var mysql = require('mysql');
var connection = mysql.createConnection({
host:'localhost',
user:'developer',
password:'superseceretpassword',
database:'testing'
});
connection.connect(function(err) {
if (err) throw err;
});
module.exports = connection;
I'm using mysql connection pool to create connection. The code looks like the following.
var pool = mysql.createPool(connectionProps);
by accessing pool, I'll get the an Object, even if the connection is not Successful. I checked it with starting and stopping mysql.
What I want is that, I need to check connection is successful or not as follows.
if(pool){ // mysql is started && connected successfully.
console.log('Connection Success');
doSomething();
}else{
console.log('Cant connect to db, Check ur db connection');
}
I want something like this. So how can we do this with the mysql pool Object. Can someone please help me?
Thanks n Regards
Commonly you would do something like select something arbitrary from the db, and catch an error if that failed. Example from the docs.
const pool = mysql.createPool(connectionProps);
pool.query('SELECT 1 + 1 AS solution', (error, results, fields) => {
if (error) throw error;
console.log('The solution is: ', results[0].solution);
});
var pool = mysql.createPool(config.db);
exports.connection = {
query: function () {
var queryArgs = Array.prototype.slice.call(arguments),
events = [],
eventNameIndex = {};
pool.getConnection(function (err, conn) {
if (err) {
if (eventNameIndex.error) {
eventNameIndex.error();
}
}
if (conn) {
var q = conn.query.apply(conn, queryArgs);
q.on('end', function () {
conn.release();
});
events.forEach(function (args) {
q.on.apply(q, args);
});
}
});
return {
on: function (eventName, callback) {
events.push(Array.prototype.slice.call(arguments));
eventNameIndex[eventName] = callback;
return this;
}
};
}
};
And require to use it like:
db.connection.query("SELECT * FROM `table` WHERE `id` = ? ", row_id)
.on('result', function (row) {
setData(row);
})
.on('error', function (err) {
callback({error: true, err: err});
});
I use the following code and it seems that the callback (Which start with Im HERE) is not called, any idea why?
console.log("im starting");
process.start(function() {
//this line doesnt called
console.log("im HERE");
server.listen(app.get('port'), function(err) {
if (err) {
console.error(err);
} else {
console.log(' listen to: ' + app.get('port'));
}
});
});
the method start are called and finish ...any idea what it can be ?
before ive added the process.start the code look like following:
And this works OK, now I need to add this process.start and when it finish to do the server.listen
module.exports = (function() {
server.listen(app.get('port'), function(err) {
if (err) {
console.error(err);
} else {
console.log('listen ' + app.get('port'));
}
});
}());
UPDATE
This is the code of process start
exports.start = function () {
Validator.validateJson(function (err) {
console.log(err);
process.exit(1);
});
plugin.parse().then(function (conf) {
require.cache.pe.configObj = conf;
}, function (err) {
console.log(err);
});
envHandler.eventE.on('AppP', function () {
console.log('User port ' + require.cache.per);
});
var run= function () {
return Promise.all([
childPro.create(path.join(value)),
childPro.findAndUpdateUser()
]).spread(function (cmd,updatedAppEnv) {
return Promise.all([childProc.executeChildProcess('exec', cmd, updatedAppEnv), Promise.delay(50).then(function (results) {
return inter.ProcessRun(val);
})]);
})
}();
}
I use promise lib like bluebird if its matter in this case
It's a bit unclear where you want to call the callback. In short, change the start function to accept a callback parameter and call callback() when you are done (or pass it at end as argument to then).
exports.start = function (callback) {
Validator.validateJson(function (err) {
console.log(err);
process.exit(1);
});
plugin.parse().then(function (configObj) {
if (typeof require.cache.persist === 'undefined') {
require.cache.persist = {};
}
require.cache.persist.configObj = configObj;
}, function (err) {
console.log(err);
});
envHandler.eventEmitterIns.on('AppPortDef', function () {
console.log('User port ' + require.cache.persist.port);
});
var run= function () {
return Promise.all([
childPro.create(path.join(value)),
childPro.findAndUpdateUser()
]).spread(function (cmd,updatedAppEnv) {
return Promise.all([childProc.executeChildProcess('exec', cmd, updatedAppEnv), Promise.delay(50).then(function (results) {
return inter.ProcessRun(val);
})]);
})
}();
run.then(callback);
}
I've node app and I want to call to function before the server is start,my questions are:
what is the recommended why to do it ?
does that can have an issue (that I call to some async function before the server is up)
Btw I use bluebird
This is my code
//This is the function which I want to call before
process.beforeProc();
//Before I start the following server
http.createServer(app).listen(app.get('port'), function (err) {
if (err) {
console.error(err);
} else {
console.log('listening on port ' + app.get('port'));
}
});
**UPDATE**
The preProcess look like following
exports.beforeProc= function () {
run.validate(function (err) {
console.log(err);
process.exit(1);
});
Parser.parse().then(function (con) {
//Cache the path values to serve new requests
if (typeof require.cache.persist === 'undefined') {
require.cache.persist = {};
}
require.cache.persist.con = con;
}, function (err) {
console.log(err);
});
.....
I don't have 50 rep so I made an answer:
Does process.beforeProc() have a callback?
If so you can do it like this:
process.beforeProc(function() {
// Once the beforeProc loaded it will return the callback, so whats
// in here
http.createServer(app).listen(app.get('port'), function (err) {
if (err) {
console.error(err);
} else {
console.log('listening on port ' + app.get('port'));
}
});
});
So I currently have two functions which are called when I add a call to a bridge, and two functions within that get called automatically, so am trying to use JQuery so they only get called when a button is clicked, and then I can work from there in the server side of things.
Issue being at the moment an error gets thrown up saying $ isnt defined.
JQuery does work I have another file am calling which is all JQuery and handles my socket.io client side.
$("#mute").click(function () {
alert("Handler for .click() called.");
channel.mute({
channelId : 111
},
function (err) {});
});
$("#kick").click(function () {
alert("Handler for .click() called.");
channel.hangup({
channelId : 111
},
function (err) {});
});
As anyone any experience using both or even have any suggestion as to how I can do this.
Full code listing(Server side);
var ari = require('ari-client');
var util = require('util');
var chanArr = [];
var test;
var mute;
var express = require('express'),
app = express(),
server = require('http').createServer(app),
io = require('socket.io').listen(server);
//ARI client
ari.connect('http://localhost:8088', 'asterisk', 'asterisk', clientLoaded);
function clientLoaded(err, client) {
if (err) {
throw err;
}
// find or create a holding bridges
var bridge = null;
client.bridges.list(function (err, bridges) {
if (err) {
throw err;
}
bridge = bridges.filter(function (candidate) {
return candidate.bridge_type === 'mixing';
})[0];
if (bridge) {
console.log(util.format('Using bridge %s', bridge.id));
} else {
client.bridges.create({
type : 'mixing'
}, function (err, newBridge) {
if (err) {
throw err;
}
bridge = newBridge;
console.log(util.format('Created bridge %s', bridge.id));
});
}
});
// handler for StasisStart event
function stasisStart(event, channel) {
console.log(util.format(
'Channel %s just entered our application, adding it to bridge %s',
channel.name,
bridge.id));
channel.answer(function (err) {
if (err) {
throw err;
}
bridge.addChannel({
channel : channel.id
}, function (err) {
var id = chanArr.push(channel.name)
console.log("Value: " + test);
test = channel.name;
updateSip);
if (err) {
throw err;
}
//If else statement to start music for first user entering channel, music will stop once more than 1 enters the channel.
if (chanArr.length <= 1) {
bridge.startMoh(function (err) {
if (err) {
throw err;
}
});
} else if (chanArr.length === 2) {
bridge.stopMoh(function (err) {
if (err) {
throw err;
}
});
} else {}
});
});
$("#mute").click(function () {
alert("Handler for .click() called.");
channel.mute({
channelId : 111
},
function (err) {});
});
$("#kick").click(function () {
alert("Handler for .click() called.");
channel.hangup({
channelId : 111
},
}
// handler for StasisEnd event
function stasisEnd(event, channel) {
console.log(util.format(
'Channel %s just left our application', channel.name));
console.log(channel.name);
var index = chanArr.indexOf(channel.name);
chanArr.splice(index, 1);
updateSip();
}
client.on('StasisStart', stasisStart);
client.on('StasisEnd', stasisEnd);
client.start('bridge-hold');
}
//Socket.io logic here
server.listen(3009, function () {
console.log('listening on *:3009');
});
app.use(express.static(__dirname + '/public'));
app.get('/', function (req, res) {
res.sendfile(__dirname + "/testPage.html");
});
io.sockets.on('connection', function (data) {
updateSip();
});
io.sockets.on('muting', function (data) {
mute = data;
console.log("client side:" + mute);
});
function updateSip() {
console.log("Value: " + test);
io.sockets.emit('sip', chanArr);
}
This is how am kicking channels from the bridge.
Am currently working on a Mute & Unmute function, but am having some troubles but this is how I kicked users via the web application
For example.
Client Side
When kick button is clicked emit the data found in TD to the server side
$(document).on('click', '.kick', function () {
var hangup = $(this).closest('td').siblings(':first-child').text();
socket.emit('hangup', hangup);
});
Server Side
Store the data received from client side into a var and then call the stasis function.
io.sockets.on('connection', function (socket) {
updateSip();
socket.on('hangup', function (data) {
hangup(data);
});
});
Stasis function
Kick the channel which you have just passed from client to server side using ARI client commands, user will be kicked and will show in stasis application.
function hangup(hangval) {
console.log("Kicked:" + hangval);
client.channels.hangup
({
channelId : hangval
},
function (err) {
if (err) {
throw err;
}
});
}
Hope this helps.