Cannot send message using exchange in node-amqp - javascript

This is my code:
var amqp = require('amqp');
var connection = amqp.createConnection( { host: 'localhost' }, { defaultExchangeName: 'testexchange' });
connection.on('ready', function () {
console.log('Connected to rabbitmq');
var exchange = connection.exchange('testexchange', {confirm:true}, function(exch){
console.log('Created exchange: ' + exch.name);
var queue = connection.queue('testqueue', { durable: true }, function(q) {
exch.publish('testqueue', {a:1}, {}, function(error) {
console.log(error);
});
});
});
});
I'm using node 0.10.2 and node-amqp 0.1.6,
I can see textexchange by rabbitmqctl list_exchanges , but there's no testqueue by rabbitmqctl list_queues, what's wrong ?

You have to define it first.
connection.queue('testqueue', { durable: true })

Related

How to pass data from net.Socket.on to an outside variable or return it

I'm working with net in node.js and I'm sending packet to a server and listening to the response, but I can't manage to return it. Here's my code:
function packetsend (sockeT, packeT) {
var resp = null;
if(sockeT) {
sockeT.write(packeT);
sockeT.on('data', (data) => {
resp = data.toString()
})
}
return resp;
}
const socket = new net.Socket();
socket.connect({host: server, port: port}, function() {
console.log('Connected');
var packetRecv = packetsend(socket, 'some packet');
if (packetRecv === 'some') {
console.log("ok");
}
})
I don't understand why packetsend() function is not returning the updated resp variable, and sends undefined object instead. When I do console.log(data) inside the sockeT.on() I see that it receives data.
Try transforming your packetsend() function in an async function. Maybe it's not returning the resp because you return it before the event 'data' is invoked.
This is just an example of a possible implementation:
function packetsend (sockeT, packeT) {
return new Promise((resolve, reject) => {
if (sockeT) {
sockeT.write(packeT);
sockeT.on('data', (data) => {
resolve(data.toString());
});
//WARNING: I don't know this 'socketT' object, don't know if there is an 'error' event.
//but it's recommended to handle errors. This is just an example.
sockeT.on('error', (error) => {
reject(error);
});
}
else{
reject('Missing sockeT');
}
});
}
const socket = new net.Socket();
socket.connect({ host: server, port: port }, function () {
console.log('Connected');
packetsend(socket, 'some packet').then(packetRecv => {
console.log('Received data => '+ packetRecv);
if (packetRecv === 'some') {
console.log("ok");
}
}).catch(error => console.log(error));
})
Update: you can also use the async/await
const socket = new net.Socket();
socket.connect({ host: server, port: port }, async function () {
try {
console.log('Connected');
let packetRecv = await packetsend(socket, 'some packet');
console.log('Received data => '+ packetRecv);
if (packetRecv === 'some') {
console.log("ok");
}
}
catch (error) {
console.log(error);
}
});
Tips:
"promise" documentation
"eventEmitter" documentation
"async/await" documentation

PeerJS not sending/receiving data

I am currently trying to make a 2 player HTML/JS boardgame and am using PeerJS to connect two players sessions together but cant get it to work.
Here is a quick test i havent been able to get to send/receive data even though connecting works
On the sending end
var peer = new Peer();
var con;
function c() {
con = peer.connect('id');
con.on('error', function(err) { alert(err); });
con.on('data', function(data){ console.log(data) });
};
function send() {
con.on('open', function(){
con.send('HELLO WORLD')
});
}
and on the receiving end:
var peer = new Peer('id');
peer.on('connection', function(con){
console.log('connected')
con.on('error', function(err) { alert(err) });
con.on('open', () => {
con.on('data', (data) => {
console.log('Incoming data', data);
con.send('REPLY');
});
});
});
You need to configure stun and turn servers for Peer. Here is complete working example.
/**********
var peer = new Peer({
config: {
'iceServers': [
{ url: 'stun:stun.l.google.com:19302' },
]
} /* Sample servers, please use appropriate ones */
*******/
<script src="https://unpkg.com/peerjs#1.3.1/dist/peerjs.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script type="text/javascript">
var peer = new Peer({
config: {
'iceServers': [
{ url: 'stun:stun.l.google.com:19302' },
]
} /* Sample servers, please use appropriate ones */
});
peer.on("open", function (id) {
$("#chat").hide()
$("#peerid").text(id)
$("form#connect").submit(function () {
var remoteID = $(this).find('input[type="text"]').val()
console.log("connect to", remoteID);
var conn = peer.connect(remoteID)
gotConnection(conn)
return false;
})
})
peer.on("connection", gotConnection)
function gotConnection(conn) {
conn.on("error", function (err) {
console.error("connection error", err, conn)
})
conn.on("open", function () {
console.log("conn open", conn)
$("#remoteid").text(conn.peer)
$("form#connect").hide()
$("#chat").show()
$("#chat form").submit(function () {
var message = $(this).find('input[type="text"]').val()
console.log("send", message);
conn.send(message)
$(this).find('input[type="text"]').val("")
$("#messages").append($('<li>' + peer.id + ': ' + message + '</li>'))
return false;
})
conn.on("data", function (data) {
console.log("got", data);
$("#messages").append($('<li>' + conn.peer + ': ' + data + '</li>'))
})
})
}
</script>

Add video to Youtube playlist NodeJS

I am currently working through the code to programmatically create a youtube playlist using a nodejs server that I received from a previous question I had and am using the working code below to do so:
var google = require('googleapis');
var Lien = require("lien");
var OAuth2 = google.auth.OAuth2;
var server = new Lien({
host: "localhost"
, port: 5000
});
var oauth2Client = new OAuth2(
'YOUR_CLIENT_ID',
'YOUR_CLIENT_SECRET',
'http://localhost:5000/oauthcallback'
);
var scopes = [
'https://www.googleapis.com/auth/youtube'
];
var youtube = google.youtube({
version: 'v3',
auth: oauth2Client
});
server.addPage("/", lien => {
var url = oauth2Client.generateAuthUrl({
access_type: "offline",
scope: scopes
});
lien.end("<a href='"+url+"'>Authenticate yourself</a>");
})
server.addPage("/oauthcallback", lien => {
console.log("Code obtained: " + lien.query.code);
oauth2Client.getToken(lien.query.code, (err, tokens) => {
if(err){
return console.log(err);
}
oauth2Client.setCredentials(tokens);
youtube.playlists.insert({
part: 'id,snippet',
resource: {
snippet: {
title:"Test",
description:"Description",
}
}
}, function (err, data, response) {
if (err) {
lien.end('Error: ' + err);
}
else if (data) {
lien.end(data);
}
if (response) {
console.log('Status code: ' + response.statusCode);
}
});
});
});
I am now moving on to the part of my project where I am in need of a way to add videos to this playlist once I have created it. The sample code that I am following along with is only written in JS and does not detail nodejs and I am therefore stuck on how to achieve this implementation with nodejs. How could I create a method like this (received from the JS implementation from the link above):
function addToPlaylist(id, startPos, endPos) {
var details = {
videoId: id,
kind: 'youtube#video'
}
if (startPos != undefined) {
details['startAt'] = startPos;
}
if (endPos != undefined) {
details['endAt'] = endPos;
}
var request = gapi.client.youtube.playlistItems.insert({
part: 'snippet',
resource: {
snippet: {
playlistId: playlistId,
resourceId: details
}
}
});
request.execute(function(response) {
$('#status').html('<pre>' + JSON.stringify(response.result) + '</pre>');
});
}
in the NodeJS language using the implementation I have already started?
I get what you mean now.If you want to add a video on your playlist then you can do that in Node using this.
youtube.playlistItems.insert({
part: 'id,snippet',
resource: {
snippet: {
playlistId:"YOUR_PLAYLIST_ID",
resourceId:{
videoId:"THE_VIDEO_ID_THAT_YOU_WANT_TO_ADD",
kind:"youtube#video"
}
}
}
}, function (err, data, response) {
if (err) {
lien.end('Error: ' + err);
}
else if (data) {
lien.end(data);
}
if (response) {
console.log('Status code: ' + response.statusCode);
}
});
If you want to render the result as HTML, First you need to use a view engine like (jade or pug) then create a template then lastly render it along with the response.
Base on your example you can do it this way:
First Create a template( Im using Pug) Save it as results.pug
html
head
title= title
body
h1= title
p=description
img(src=thumbnails.medium.url)
Then update your code below:
var google = require('googleapis');
var Lien = require("lien");
var OAuth2 = google.auth.OAuth2;
var pug = require('pug')
var server = new Lien({
host: "localhost"
, port: 5000,
views:{
path:__dirname,
name:'pug'
}
});
var oauth2Client = new OAuth2(
'YOUR_CLIENT_ID',
'YOUR_CLIENT_SECRET',
'http://localhost:5000/oauthcallback'
);
var scopes = [
'https://www.googleapis.com/auth/youtube'
];
var youtube = google.youtube({
version: 'v3',
auth: oauth2Client
});
server.addPage("/", lien => {
var url = oauth2Client.generateAuthUrl({
access_type: "offline",
scope: scopes
});
lien.end("<a href='"+url+"'>Authenticate yourself</a>");
})
server.addPage("/oauthcallback", lien => {
console.log("Code obtained: " + lien.query.code);
oauth2Client.getToken(lien.query.code, (err, tokens) => {
if(err){
return console.log(err);
}
oauth2Client.setCredentials(tokens);
youtube.playlists.insert({
part: 'id,snippet',
resource: {
snippet: {
title:"Test",
description:"Description",
}
}
}, function (err, data, response) {
if (err) {
lien.end('Error: ' + err);
}
else if (data) {
//lien.end(data);
lien.render('results',data.snippet)
}
if (response) {
console.log('Status code: ' + response.statusCode);
}
});
});
});
The things that I update on your code are:
var server = new Lien({
host: "localhost"
, port: 5000,
views:{
path:__dirname,
name:'pug'
}
});
And
//lien.end(data);
lien.render('results',data.snippet)

Couchdb `nano` module - Unhandled rejection - is not a function at Object

I Added Couchdb Update Function to my Code and is ok But When I use That inside of bot.onText(/^[\/!#]start$/, msg => { I Have This Error:
Unhandled rejection TypeError: alice.update is not a function
at Object.bot.onText.msg [as callback]
How Should I Solve That?
This is My Code:
var nano = require('nano')('http://localhost:5984');
// clean up the database we created previously
nano.db.destroy('alice', function() {
// create a new database
nano.db.create('alice', function() {
var alice = nano.use('alice');
///// update Function
alice.update = function(obj, key, callback){
var db = this;
db.get(key, function (error, existing){
if(!error) obj._rev = existing._rev;
db.insert(obj, key, callback);
});
};
});
});
bot.onText(/^[\/!#]start$/, msg => {
///// using update
var alice = nano.use('alice');
alice.update({ crazay: true }, 'rabbit', function(err, body, header) {
if (err) {
console.log('[alice.insert] ', err.message);
return;
}
console.log('you have updated the rabbit.')
console.log(body);
});
const opts = {
reply_to_message_id: msg.message_id,
reply_markup: JSON.stringify({
keyboard: [['TEST']],
resize_keyboard:true,
one_time_keyboard: true
})
};
bot.sendMessage(msg.chat.id, `Stored In DB`, opts);
});
Solved By Myself, You Should Put Update Function Inside of bot.onText
var nano = require('nano')('http://localhost:5984');
// clean up the database we created previously
nano.db.destroy('alice', function() {
// create a new database
nano.db.create('alice', function() {
var alice = nano.use('alice');
});
});
bot.onText(/^[\/!#]start$/, msg => {
///// using update
var alice = nano.use('alice');
///// update Function
alice.update = function(obj, key, callback){
var db = this;
db.get(key, function (error, existing){
if(!error) obj._rev = existing._rev;
db.insert(obj, key, callback);
});
};
alice.update({ crazay: true }, 'rabbit', function(err, body, header) {
if (err) {
console.log('[alice.insert] ', err.message);
return;
}
console.log('you have updated the rabbit.')
console.log(body);
});
const opts = {
reply_to_message_id: msg.message_id,
reply_markup: JSON.stringify({
keyboard: [['TEST']],
resize_keyboard:true,
one_time_keyboard: true
})
};
bot.sendMessage(msg.chat.id, `Stored In DB`, opts);
});

angular promises and nodejs http get response

I would use the promises of angularJS to fill data to a grid. I'd like to load data "row by row" as soon as the nodeJS's server, on which use the module "mssql" with the "stream" enabled, back to client every single line from the DB.
On the client side I use these functions:
function asyncGreet() {
var deferred = $q.defer();
var _url = 'http://localhost:1212/test';
$http.get(_url).
then(function(result) {
deferred.resolve(result);
}, function(error) {
deferred.reject(error);
}, function(value) {
deferred.notify(value); //<<-- In "value" I would like to get every single row
});
return deferred.promise;
}
$scope.btnTest = function () {
var promise = asyncGreet();
promise.then(function(res) {
console.log('Success: ' + res.data + "\n");
}, function(reason) {
console.log('Failed: ' + reason);
}, function(update) {
console.log('Got notification: ' + update); //<<--
});
};
On nodeJS server those:
app.get('/test', function (req, res) {
//sql for test
var _query = 'select top 50 * from tb_test';
var sql = require('mssql');
var connection;
var config = {
user: 'testUser',
password: '12345',
server: 'localhost\\test',
database: 'testDB',
stream: true
};
connection = new sql.Connection(config, function (err) {
var request = new sql.Request(connection);
request.query(_query);
request.on('recordset', function(columns) {
// Emitted once for each recordset in a query
//res.send(columns);
});
request.on('row', function(row) {
res.write(JSON.stringify(row)); //<<-- I would like intercept this event on client side
// and get the result in my angularJS function on deferred.notify
});
request.on('error', function(err) {
// May be emitted multiple times
console.error(err)
});
request.on('done', function(returnValue) {
// Always emitted as the last one
res.end('DONE');
});
});
});
Anyone can help me with this?
Thanks!
I'm done it using socket.io :)
On angularJS side:
// count the row for test only
$scope.count = 0;
$scope.prova = function () {
mySocket.emit('getTableByRow', {});
mySocket.on('resRow', function (data) {
if (data.event == 'ROW') {
$scope.count += 1;
}else {
$scope.count += " !!DONE!! ";
}
});
};
On NodeJS side:
[ ... connection with DB ... ]
io.on('connection', function (socket) {
socket.on('getTableByRow', function (data) {
_getTableByRow(socket, data);
});
});
_getTableByRow function:
var _getTableByRow = function (socket, data) {
var _query = 'select top 50 * from tb_test';
request.query(_query);
request.on('row', function(row) {
// return only the ids for test
socket.emit('resRow', {event: 'ROW', data: row.id.toString()});
});
request.on('done', function(returnValue) {
socket.emit('resRow', {event: 'DONE'});
});
request.on('recordset', function(columns) {
console.log(columns);
});
request.on('error', function(err) {
socket.emit('resRow', {event: 'ERROR', data: err});
});
}
In this way, as soon as one row is read from the DB, it is immediately sent to the client :)

Categories

Resources