socket.io Expanding the original client js library - javascript

This is my original client code
var socket = io.connect('http://localhost:7048');
socket.on('channel', function (mess) {
console.log(mess);
});
socket.on('message', function (mess) {
console.log(mess);
});
How can I extend the original library so that you get something like this. Such code is used by pubnub.
var myPlugin = MYPLUGIN({
host: 'http://localhost:7048'
});
myPlugin.listen({
channel: 'channel',
message: function(m){console.log(m)},
error: function(m){console.log(m)}
});
myPlugin.listen({
channel: 'message',
message: function(m){console.log(m)},
error: function(m){console.log(m)}
});
myPlugin.unlisten({
channel : 'message',
});

If you're trying to make it like the code on pubnub just because pubnub uses this kind of syntax and you're used to it, I don't recommend on doing it, but if you have an API and you need to have a certain architecture then that's fine.
I recommend building a wrapper.
function MyPlugin(hostObj) {
function listen(listenObj) {
//your code here
}
function unlisten(unlistenObj) {
//your code here
}
//this makes your functions public
Object.defineProperties(this, {
"listen": {value: listen},
"unlisten": {value: unlisten}
});
return this;
}

Related

Electron js win.webContents.print callback function doesn't work?

I am working on an application with Electron js and Vue js. I need to print the Synchronous request sent by Renderer with the print function. According to the result, I have to transmit the result to the renderer over the backend. Therefore, I use the callback function of the print function. But when I use this function, the print method does not work. I shared the codes below. Could there be an error?
ipcMain.on("set-print", function(event, arg) {
let options = {
silent: true,
deviceName: arg,
};
win.webContents.print(options, function(success) {
event.returnValue = success;
});
});
Try Promise function
win.webContents.print(options)
.then((success)=>{
console.log(success);
})
.catch((err)=>{
console.log(err)
});
https://www.electronjs.org/docs/api/webview-tag#webviewprintoptions

Meteor/mongoDb find and update

I'm just learning Meteor and I made a little app but I have a problem with find() and update() collection on server side
For example:
if (Meteor.isServer) {
function getCollection1(){
return collection_1.find({}).fetch({});
}
....
Meteor.methods({
start: function(id) {
datas = getCollection1();
Collection2.update({_id:id}, {$set: {datas: datas}}); //sometimes it's ok(3/4)
}
...
}
Or when I await, I have an error
if (Meteor.isServer) {
async function getCollection1(){
return await collection_1.find({}).fetch({});
}
....
Meteor.methods({
start: function(id) {
getCollection1().then(function(datas){
Rooms.update({_id: id}, {$set: {datas: datas}},function(err){
console.log(err);//error: Meteor code must always run within a fiber
});
});
}
...
}
What did I do wrong?
EDIT
it seems to work well with Fiber()
if (Meteor.isServer) {
Fiber = Npm.require('fibers')
function getCollection1(){
return collection1.find({}).fetch({});
}
function setCollection2(id){
Fiber(function() {
datas = getCollection1();
collection2.update({_id: id}, {$set: {datas: datas}},function(err){
console.log(err);
});
}).run();
}
....
Meteor.methods({
start: function(id) {
setCollection2(id);
}
...
}
With the async/await version, you do not need to use Fiber. Instead you could this Meteor function: Meteor.bindEnvironment to make it work:
// ...
getCollection1().then(Meteor.bindEnvironment(function(datas){
Rooms.update(// ...);
}));
// ...
For a more understandable explanation, you could consult this video:
What is Meteor.bindEnvironment?
Based on the code you provided, my guess is that for the first example the "Collection2.update" is taking place before GetCollection1() is completed. If this is indeed the case, then on the client side when you subscribe to the collection be sure to have a way to "wait" for the subscription to complete.
For example something like this on the client side where "start()" is called...
const handle = Meteor.subscribe( 'collection_1' );
if ( handle.ready() ) {
Meteor.call('start');
} else {
const allusers = Meteor.users.find().fetch();
onData( null, {allusers} );
}
Again, this is my best guess as you did not post the error you received with your first code chunk and I can't speak for the second you in which you've attempted to implement this.

Babel causing Uncaught TypeError in transpiled ES5 Vue component code

Working on a small Node.js project that needs to send JSON objects over sockets. I discovered that JsonSocket (https://github.com/sebastianseilund/node-json-socket) served my needs and running the simple server/client demos provided by that author works great.
I am adapting the demo Client code (https://github.com/sebastianseilund/node-json-socket#simple-clientserver-example) to a Vue.js-Babel-Browserify project framework and placing the code in a .vue component file. Changes primarily involve passing data from an HTML text field (default text included in the binding data parameter) to the listening server via a socket connection, triggered by an HTML button. But I'm not getting beyond the button trigger at this point.
What I am getting is: Uncaught TypeError: _net2.default.Socket is not a constructor when sending the data over the socket with this transpiled code: var socket = new _jsonSocket2.default(new _net2.default.Socket());
Below is the original .vue code:
import net from 'net'
import JsonSocket from 'json-socket'
export default {
data () {
return {
header: 'Login',
messageStuff: '{ "cmd": "send", "what": { "this": "that" } }'
}
},
methods: {
submitMessage() {
var stuff = JSON.parse(this.messageStuff)
var port = 8069
var host = '192.168.11.5'
var socket = new JsonSocket(new net.Socket()) <-- *** source of the culprit! ***
socket.connect(port, host)
socket.on('connect', function () {
socket.sendMessage(stuff)
socket.on('message', function (message) {
console.log('Server replies...')
console.dir(message)
})
})
}
}
}
And here is the transpiled code of the relevant section of the script:
var _net = require('net');
var _net2 = _interopRequireDefault(_net);
var _jsonSocket = require('json-socket');
var _jsonSocket2 = _interopRequireDefault(_jsonSocket);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.default = {
data: function data() {
return {
header: 'Login',
messageStuff: '{ "cmd": "send", "what": { "this": "that" } }'
};
},
methods: {
submitMessage: function submitMessage() {
var stuff = JSON.parse(this.messageStuff);
var port = 8069;
var host = '192.168.11.5';
var socket = new _jsonSocket2.default(new _net2.default.Socket()); <-- *** the culprit! ***
socket.connect(port, host);
socket.on('connect', function () {
socket.sendMessage(stuff);
socket.on('message', function (message) {
console.log('Server says...');
console.dir(message);
});
});
}
}
};
})()
Not sure why Babel mangled the line (where the <--- mark is in the code in both windows).
Somehow I feel that this is related to Unexpected "Uncaught TypeError: XXX is not a constructor" errors with Babel and ES6 but in that case the solution revolved around adding access the default property in a require statement. I'm not sure how I could accomplish the same with import inside the vue component.
Any prodding in the right direction would be appreciated.

Meteor how to Get Variable Value from Server to Client?

Hei,
Im stuck for some reason. Im playing around with Arduino board and I want to read the data in the client.
My server code is this:
if(Meteor.isServer) {
var five = Meteor.npmRequire("johnny-five");
var board = new five.Board();
Meteor.startup(function() {
board.on("ready", Meteor.bindEnvironment(function() {
var temperature = new five.Thermometer({
controller: 'TMP36',
pin: 'A0'
});
Meteor.setInterval(function() {
console.log(temperature.celsius);
}, 5000);
}))
})
}
I don't want to save the data to collection but to read it online. How do I pass the variable temperature.celsius from server to the client? I cannot run the code in the client since i'm using NPM require and it works only in the server.
Right after the Meteor.setInterval definition, add this:
Meteor.methods({
temperature: function () {
return temperature;
},
});
Then add, at the bottom of your code:
if (Meteor.isClient) {
Template.tempReport.result = function () {
return Session.get('temperature') || "";
};
Template.tempReport.events = {
'click button' : function () {
Meteor.call('temperature',function(err, response) {
Session.set('temperature', response);
});
}
};
}
And finally in your HTML:
<template name="tempReport">
<div>Temperature: {{temperature}} <button>Update</button></div>
</Template>

XMPP: AngularJS + Strophe

The basic XMPP with strophe and javascript wants to convert to AngularJS.
.controller('loginCtrl', function(xmppAuth) {
xmppAuth.auth(login, password);
})
and in service:
.service('xmppAuth', function() {
.return {
auth: function(login, password) {
connect = new Strophe.Connection(domain);
connect.connect(login, password, function (status) {
if (status === Strophe.Status.CONNECTED) {
connect.addHandler(on_roster_changed,"jabber:iq:roster", "iq", "set");
connect.addHandler(on_iq, null, "iq","");
connect.addHandler(on_presence, null, "presence");
connect.addHandler(on_message, null, 'message', '');
}
}
}
}
})
in js file
var on_presence = function(presence){
code
}
when i run this there is no error. But all handling events like on_presence() method called only once. this is handler event of Strophe Connection object. Is there is any remain in this code or what should i do for handling strophes event with angularJS?
I refered This Link but it not works.
See the Strophe.js docs for addHandler:
The handler should return true if it is to be invoked again; returning false will remove the handler after it returns.
Therefore, your on_presence code should return true if you want it to be invoked again:
var on_presence = function(presence) {
// do some stuff
return true;
};

Categories