NodeJS unable to modify a class obj - javascript

this is my first post in this forum. So please forgive me the misstakes.
I want to write a NodeJS server which runs a WebSocket Server (npm ws module).
The NodeJS server contains also a Class Obj which i want to modify a funciton afterwards over the Websocket server.
My Problem is the modified functjion cant acces global variables.
Can someone help if there is a solution for this problem or why this happes because if you do this without the Websocket it works.
Here is the code:
Server code:
const WebSocket = require('ws');
// WebSocket Server
const wss = new WebSocket.Server({ port: 8080 });
wss.on('connection', function connection(ws) {
ws.on('message', function incoming(message) {
try {
message = JSON.parse(message);
if (message.type == "handler") {
handler.modify(message.data);
console.log("modifyed");
}
if (message.type == "func") {
handler.modify_func(message.data);
console.log("modifyed");
}
if (message.type == "run") {
eval(message.data);
}
}
catch (error) {
}
});
});
// Modifying class
class Handler {
constructor() {
this.functions = [];
}
modify(data) {
let temp_class = new Function('return ' + data)();
temp_class.functions.forEach(element => {
if (this.functions.indexOf(element) == -1) {
this.functions.push(element)
}
this[element] = temp_class[element];
});
}
modify_func(data) {
let temp_func = new Function('return ' + data)();
this[temp_func.name] = temp_func;
}
test_func_from_orginal() {
console.log("test_func_from_orginal says:");
console.log(test_val);
}
}
var test_val = "this is the global variable";
var handler = new Handler();
Client code:
const WebSocket = require('ws');
//WebSocket Client
var ws = new WebSocket('ws://localhost:8080');
ws.on('open', function open(event) {
// ws.send(JSON.stringify({ type: "handler", data: Handler.toString() }))
ws.send(JSON.stringify({ type: "func", data: test_func_from_func.toString() }))
console.log("open")
});
//Class Module
class Handler {
static get functions() {
return ["test"];
}
static test_func_from_class() {
console.log("test_func_from_class sayes:")
console.log(test_val);
}
}
function test_func_from_func() {
console.log("test_func_from_func sayes:")
console.log(test_val);
}
setTimeout(function () { ws.send(JSON.stringify({ type: "run", data: 'handler.test_func_from_orginal()' })) }, 1000);
// setTimeout(function () { ws.send(JSON.stringify({ type: "run", data: 'handler.test_func_from_class()' })) }, 1000);
setTimeout(function () { ws.send(JSON.stringify({ type: "run", data: 'handler.test_func_from_func()' })) }, 1000);

Ok, so this is what it's all about - a simple mistake. If you cut out all the websocket stuff (which is not really relevant here, as strings, and not contexts, got passed from and back anyway), you'll get this:
class ServerHandler {
constructor() {
this.functions = [];
}
modify(data) {
let temp_class = new Function('return ' + data)();
// not sure why not just `eval(data)` btw
temp_class.functions.forEach(funcName => {
if (this.functions.indexOf(funcName) == -1) {
this.functions.push(funcName)
}
this[funcName] = temp_class[funcName];
});
}
}
class ClientHandler {
static get functions() {
return ["test_func_from_class"];
// not "test" as in your example
// you actually don't even need this registry:
// all the static methods can be collected in runtime
}
static test_func_from_class() {
console.log("test_func_from_class sayes:")
console.log(test_val);
}
}
var test_val = 42;
var handler = new ServerHandler();
handler.modify(ClientHandler.toString());
eval(`handler.test_func_from_class()`); // 42
This all works fine, as there's no longer a mismatch between a name of method stored in static get functions ("test") and actual name of that method ("test_func_from_class"). The trick is that all the static functions created along with that temporary class are scoped the same way any other entity created in ServerHandler; that's how they 'see' that test_val.
But 'works' here is about mere possibility of this approach from technical perspective, and not about feasibility. Both new Function and eval with arbitrary input are very dangerous security holes - and they're left wide open here.

I found now a solution for my problem.
Server Code
const WebSocket = require('ws');
// WebSocket Server
const wss = new WebSocket.Server({ port: 8080 });
wss.on('connection', function connection(ws) {
ws.on('message', function incoming(message) {
message = JSON.parse(message);
try {
if (message.type == "run") {
eval(message.data);
}
if (message.type == "obj_handler") {
handler.modify(JSON.parse(message.data));
}
}
catch (error) {
console.log(error);
}
// console.log('received: %s', message);
});
ws.send('something');
});
class ServerHandler {
constructor() {
this.data = "hi";
}
modify(data) {
for (const func in data) {
this[func] = eval(data[func]);
}
}
}
var test_val = 42;
var handler = new ServerHandler();
Client Code:
const WebSocket = require('ws');
//WebSocket Client
try {
var ws = new WebSocket('ws://localhost:8080');
ws.on('open', function open(event) {
ws.send(JSON.stringify({ type: "obj_handler", data: update.convert() }))
});
}
catch (error) {
}
// Needed Update with 2 new Functions
update = {
func_test_global: () => {
console.log(test_val);
},
func_test_this: _ => {
console.log(this.data);
},
convert: function () {
let new_update = {};
for (const func in this) {
if (func != "convert")
new_update[func] = "" + this[func];
}
return JSON.stringify(new_update)
}
}
// setTimeout(function () { ws.send(JSON.stringify({ type: "run", data: 'handler.func_test_global()' })) }, 1000);
// setTimeout(function () { ws.send(JSON.stringify({ type: "run", data: 'handler.func_test_this()' })) }, 1000);

Related

How to identify if this code for implementing webrtc is working correctly?

I'm currently working on a webrtc project that was written before from another developer.
While I'm currently new to webrtc and I tried hard to make it work after deleting obsolete functions and other things, now can I identify what is wrong here in my steps?
I'm following steps in here
my code here is about trigger .call button
$(dod)
.find(".call")
and I run throw signaling
wbsc.emit("SEND_EVENT_EMIT_CALL_AUDIO", {
data: { type: "login", id: id },
});
$(dod).hide();
//call*donecallProccess 1
setTimeout(() => {
wbsc.emit("SEND_EVENT_EMIT_CALL_AUDIO", {
data: { type: "doneoif", id: id },
});
}, 2e3);
that can trigger and process here
case "donecall":
call(data.id);
break;
case "showcall":
handleLogin(data.success, data.id);
break;
case "offercall":
handleOffer(data.offer, data.name);
break;
case "answercall":
handleAnswer(data.answer);
break;
case "candidatecall":
handleCandidate(data.candidate);
break;
case "leavecall":
handleLeave();
then this code run one after each handle login and getUserMediaSuccess
gather permission from media stream and create a new RTCPeerConnection(servers)
get tracks from my streams with addtrack if I implement it correctly
and if ontrack happened can I collect streaming to add to remote peer like this way or should just add
yourConn.ontrack = (event) => {
if (event.candidate !== null) {
remoteVideo.srcObject = event.streams[0];
} else {
console.log("there is an error with on trackevent", event);
}
};
complete code for previous handlelogin and call is
let handleLogin = async (success) => {
try {
if (success) {
localVideo = document.getElementById("wbrtclocal");
remoteVideo = document.getElementById("wbrtcremote");
var getUserMedia = navigator.mediaDevices.getUserMedia|| navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia ;
if (getUserMedia) {
getUserMedia({
audio: { noiseSuppression: false },
})
.then(getUserMediaSuccess)
.catch(errorHandler);
} else {
alert("Your browser does not support getUserMedia API");
}
} else {
alert("Ooops...try a different username");
}
} catch (err) {
errorHandler(error);
}
};
let getUserMediaSuccess = async (streams) => {
try {
yourConn = new RTCPeerConnection(servers);
if(streams){
localStream = streams;
localVideo.srcObject = streams;
streams.getTracks().forEach((track) => yourConn.addTrack(track, streams));
}
yourConn.onicecandidate = (event) => {
if (event.candidate) {
wbsc.emit("SEND_EVENT_EMIT_CALL_AUDIO", {
data: {
type: "candidate",
candidate: event.candidate,
id: connectedUser,
},
});
}
console.log("nwe ice candidate is", event.candidate);
console.log("nwe stream is", streams);
};
remoteStream = new MediaStream();
remoteVideo.srcObject = remoteStream;
yourConn.ontrack = (event) => {
if (event.candidate !== null) {
event.streams[0].getTracks().forEach((track) => {
remoteStream.addTrack(track);
});
} else {
console.log("there is an error with on trackevent", event);
}
};
} catch (err) {
errorHandler(error);
}
console.log("stream is", streams);
};
call function
async function call(id) {
$("#videoCall").show();
if (id.length > 0) {
connectedUser = id;
try {
RTCPeerConnection.createOffer().
offer.
await yourConn
.createOffer()
.then((offer) => successCallback)
.catch((e) => {
fl(e);
});
let successCallback = async (offer) => {
try {
yourConn
.setLocalDescription(offer)
.then(
wbsc.emit("SEND_EVENT_EMIT_CALL_AUDIO", {
data: { type: "offer", offer: offer, id: connectedUser },
})
)
.catch((e) => {
fl(e);
});
} catch (e) {
fl(e);
}
};
} catch (e) {
fl(e);
}
const user = U_CASH[id];
if (user) {
$("#videoCall")
.find(".u-pic")
.css("background-image", "url(" + removegifpic(user.pic + ")"));
$("#videoCall").find(".u-topic").text(user.topic);
}
$(".statecall").text("جاري الإتصال");
hl($(".statecall"), "warning");
} else {
alert("username can't be blank!");
}
console.log("connectedUser", id);
console.log("offer", offer);
console.log();
console.log();
console.log();
}
and this about each one for those
[handleOffer , handleAnswer , handleCandidate , handleLeave]
let handleOffer = async (offer, name) => {
$("#callvideonot").show();
const user = U_CASH[name];
if (user) {
$("#callvideonot")
.find(".u-pic")
.css("background-image", "url(" + removegifpic(user.pic + ")"));
$("#callvideonot").find(".u-topic").text(user.topic);
}
$(".callvideoaccept").on("click", async () => {
connectedUser = name;
await yourConn.setRemoteDescription(offer);
yourConn
.createAnswer()
.then((answer) => t.setLocalDescription(answer))
.then(() => {
wbsc.emit("SEND_EVENT_EMIT_CALL_AUDIO", {
data: { type: "answer", answer: answer, id: connectedUser },
});
})
.catch(fl);
const user = U_CASH[name];
if (user) {
$(".statecall").text("متصل");
hl($(".statecall"), "success");
$("#videoCall")
.find(".u-pic")
.css("background-image", "url(" + removegifpic(user.pic + ")"));
$("#videoCall").find(".u-topic").text(user.topic);
}
$("#callvideonot").hide();
$("#videoCall").show();
});
$(".callvideodeny").on("click", function () {
wbsc.emit("SEND_EVENT_EMIT_CALL_AUDIO", {
data: { type: "leave", id: name },
});
});
};
let handleAnswer = async (answer) => {
try {
$(".statecall").text("متصل");
hl($(".statecall"), "success");
//here we delete new RTCSessionDescription because constructor is deprecated.
await yourConn.setRemoteDescription(answer);
} catch (e) {
fl(e);
}
};
let handleCandidate = async (candidate) => {
try {
var NewlyIceCandidate = new RTCIceCandidate(candidate)
.setRemoteDescription().
await yourConn.addIceCandidate(NewlyIceCandidate);
} catch (e) {
fl(e);
}
};
function handleLeave() {
$("#callvideonot").hide();
$(".statecall").text("رفض");
hl($(".statecall"), "danger");
$(".vloumemic").removeClass("fa-volume-off");
$(".vloumemic").addClass("fa-volume-up");
$(".mutemic").removeClass("fa-microphone-slash");
$(".mutemic").addClass("fa-microphone");
setTimeout(() => {
$("#videoCall").hide();
}, 1e3);
if (localStream) {
localStream.getTracks().forEach((e) => e.stop());
}
if (connectedUser) {
connectedUser = null;
}
remoteVideo.src = null;
if (yourConn) {
yourConn.close();
yourConn.onicecandidate = null;
yourConn.ontrack = null;
localStream = null;
}
}
in here here number 7 instruction they said should I add Wait for an incoming remote SDP description from the signaling service and set it using RTCPeerConnection.setRemoteDescription(). as the caller where can I add it? in handleCandidate function?
and in the callee side number 1 instruction the said that I should
Create a new RTCPeerConnection instance with the appropriate ICE configuration.
can I reuse
yourConn = new RTCPeerConnection(servers);
or should instantiate a new one to prevent conflict in website server process
as a not yourConn it's global value and in top level of this file and reuse it over all
the connection, is peers 2 or the callee should have another new RTCPeerConnection?
and for remoteVideo.srcObject = remoteStream; the remoteStream value is global and I overwrite it. can I here add new media stream or just it's good to dealing with the present one which is remoteVideo element?
// remoteStream = new MediaStream();
remoteVideo.srcObject = remoteStream;
the issue that was here is to split the RTCPeerConnection object and just create new one for each peer local and remote that what i did and it working corectly after i remove addtrack completly and replace it with addtranceiver and gettranceiver
u can find it here from previous issue's answer and i fix it here
and no need to overwrite or reset the srcObect value. The track transition on receiver side in the same MediaStream should be "seamless" RTCRtpSender.replaceTrack
This allows you to seamlessly change which track is being sent without having to renegotiate at the expense of another offer/answer cycle

Broadcasting to all clients with Deno websocket

I want to add notifications to an application I've developed.
Unfortunately, Deno has removed the ws package.(https://deno.land/std#0.110.0/ws/mod.ts)
That's why I'm using the websocket inside the denon itself. Since it doesn't have many functions, I have to add some things myself.
For example, sending all messages to open clients.
What I want to do is when the pdf is created, a (data, message) comes from the socket and update the notifications on the page according to the incoming data.
I keep all open clients in a Map. and when the pdf is created, I return this Map and send it to all sockets (data, message).
However, this works for one time.
server conf...
import {
path,
paths,
ctid,
} from "../deps.ts";
const users = new Map();
const sockets = new Map()
const userArr = [];
export const startNotif = (socket,req) => {
const claims = req.get("claims");
const org = req.get("org");
claims.org = org;
console.log("connected")
users.set(claims.sub, {"username":claims.sub,"socket":socket})
users.forEach((user)=>{
if(userArr.length === 0){
userArr.push(user)
}
else if(userArr.every((w)=> w.username !== user.username) )
userArr.push(user)
})
sockets.set(org, userArr)
function broadcastMessage(message) {
sockets.get(org).map((u)=>{
console.log(u.socket.readyState)
u.socket.send(message)
})
}
if (socket.readyState === 3) {
sockets.delete(uid)
return
}
const init = (msg) => {
socket.send(
JSON.stringify({
status: "creating",
})
);
};
const ondata = async (msg) => {
const upfilepath = path.join(paths.work, `CT_${msg.sid}_report.pdf`);
try {
const s=await Deno.readTextFile(upfilepath);
if(s){
socket.send(
JSON.stringify({
status: "end",
})
);
} else {
socket.send(
JSON.stringify({
status: "creating",
})
);
}
} catch(e) {
if(e instanceof Deno.errors.NotFound)
console.error('file does not exists');
}
};
const end = () => {
try {
const endTime = Date.now()
const msg = "Your PDF has been created"
const id = ctid(12) // random id create
broadcastMessage(
JSON.stringify({
id: id,
date: endTime,
status: "done",
message: msg,
read: 'negative',
action: 'pdf'
})
);
} catch (e) {
console.log(400, "Cannot send.", e);
}
}
socket.onmessage = async (e) => {
const cmd = JSON.parse(e.data);
if(cmd.bid === 'start'){
await init(cmd)
}
if(!cmd.bid && cmd.sid){
await ondata(cmd)
}
if(cmd.bid === 'end'){
await end();
}
}
socket.onerror = (e) => {
console.log(e);
};
}
client conf...
export const webSocketHandler = (request) =>
new Promise((res, rej) => {
let url;
if (!process.env.NODE_ENV || process.env.NODE_ENV === 'development') {
url = `http://localhost:8080/api/notifications/ws`.replace('http', 'ws');
} else {
url = `${window.location.origin}/api/notifications/ws`.replace('http', 'ws');
}
const token = JSON.parse(sessionStorage.getItem('token'));
const orgname = localStorage.getItem('orgname');
const protocol = `${token}_org_${orgname}`;
const socket = new WebSocket(url, protocol);
const response = Object.create({});
socket.onopen = function () {
socket.send(
JSON.stringify({
bid: 'start',
})
);
};
socket.onmessage = function (event) {
response.data = JSON.parse(event.data);
if (response.data.status === 'creating') {
socket.send(
JSON.stringify({
sid: request.sid,
})
);
} else if (response.data.status === 'end') {
socket.send(
JSON.stringify({
bid: 'end',
})
);
} else if (response.data.status === 'done') {
try {
res(response);
} catch (err) {
rej(err);
}
}
};
socket.onclose = function (event) {
response.state = event.returnValue;
};
socket.onerror = function (error) {
rej(error);
};
});
onclick function of button I use in component...
const donwloadReport = async (type) => {
const query = `?sid=${sid}&reportType=${type}`;
const fileName = `CT_${sid}_report.${type}`;
try {
type === 'pdf' && setLoading(true);
const response = await getScanReportAction(query);
const request = {
sid,
};
webSocketHandler(request)
.then((data) => {
console.log(data);
dispatch({
type: 'update',
data: {
id: data.data.id,
date: data.data.date,
message: data.data.message,
action: data.data.action,
read: data.data.read,
},
});
})
.catch((err) => {
console.log(err);
});
if (type === 'html') {
downloadText(response.data, fileName);
} else {
const blobUrl = await readStream(response.data);
setLoading(false);
downloadURL(blobUrl, fileName);
}
} catch (err) {
displayMessage(err.message);
}
};
Everything works perfectly the first time. When I press the download button for the pdf, the socket works, then a data is returned and I update the notification count with the context I applied according to this data.
Later I realized that this works in a single tab. When I open a new client in the side tab, my notification count does not increase. For this, I wanted to keep all sockets in Map and return them all and send a message to each socket separately. But in this case, when I press the download button for the second time, no data comes from the socket.
Actually, I think that I should do the socket initialization process on the client in the context. When you do this, it starts the socket 2 times in a meaningless way.
In summary, consider an application with organizations and users belonging to those organizations. If the clients of A, B, C users belonging to X organization are open at the same time and user A pressed a pdf download button, I want A, B, C users to be notified when the pdf is downloaded.
I would be very grateful if someone could show me a way around this issue.
Have you looked at the BroadcastChannel API? Maybe that could solve your issue. See for example:
Deno specific: https://medium.com/deno-the-complete-reference/broadcast-channel-in-deno-f76a0b8893f5
Web/Browser API: https://developer.mozilla.org/en-US/docs/Web/API/Broadcast_Channel_API

How to separate clients in an event based websocket implementation?

I'm writing my own event-based websocket wrapper, based on the ws package for node and having trouble separating clients on the server side.
I set up a test scenario where my client emits a message to the server and the server sends a "ping" back to that same client.
What happens is that my test scenario works perfectly with the first connected client, but as soon as another client connects, emit messages from the first client will ping to the other client (messages from second client will correctly ping to the second client).
It feels like the WebSocket is somehow shared between the two clients but I can't seem to find where this is happening.
//SERVER CODE
let events = {};
function WebSockServer(port) {
//Init server
const wss = new WebSocket.Server({
port,
clientTracking: true
}, () => {
if (events['open']) {
events['open'].callback();
}
});
wss.on('connection', ws => {
ws.id = uuidv4();
let sock = new WebSock(ws, wss);
if (events['connection']) {
events['connection'].callback(sock);
}
ws.on('message', json => {
console.log('received message from ' + ws.id);
const message = JSON.parse(json);
//Check flags
for (let key in message.flags) {
if (key === 'binary' && message.flags[key].length > 0) {
message.flags[key].forEach(binary => {
const parsed = Buffer.from(message.data[binary], 'utf-16');
message.data[binary] = parsed;
});
}
}
//Check if event handler exists & check if event is only to be triggered once
if (events[message.event] && !events[message.event].once) {
events[message.event].callback(message.data);
}
else if (events[message.event] && events[message.event].once) {
events[message.event].callback(message.data);
delete events[message.event];
}
else {
return;
}
});
ws.on('close', () => {
if (events['close']) {
console.log('client disconnected');
events['close'].callback(ws.id);
}
wss.clients.delete(ws);
});
});
//Create an event handler
this.on = function on(event, callback) {
events[event] = {callback, once: false};
return this;
}
wss.on('error', err => {
console.log('Server shut down.');
});
}
function WebSock(ws, wss) {
this.ws = ws;
this.id = ws.id;
//Create an event handler
this.on = function on(event, callback) {
events[event] = {callback, once: false};
return this;
}
//Create an event handler for one time use
this.once = function once(event, callback) {
events[event] = {callback, once: true};
return this;
}
//Emit message to socket
this.emit = function emit(event, data) {
let flags = {
binary: []
};
//Check for binary data
for (let key in data) {
if (Buffer.isBuffer(data[key])) {
const stringified = data[key].toJSON();
data[key] = stringified;
flags.binary.push(key);
}
}
const payload = JSON.stringify({event, data, flags});
this.ws.send(payload);
return this;
}
//Emit message to specific socket
this.emitTo = function emitTo(id, event, data) {
let destination;
let flags = {
binary: []
};
//Find socket
for (let socket of wss.clients) {
if (socket.id === id) {
destination = socket;
break;
}
}
//Check for binary data
for (let key in data) {
if (Buffer.isBuffer(data[key])) {
const stringified = data[key].toJSON();
data[key] = stringified;
flags.binary.push(key);
}
}
//Send message to socket
if (destination) {
//Check type
if (typeof event != 'string' || typeof data != 'object') {
throw new TypeError('event must be a string, data must be an object');
}
const payload = JSON.stringify({event, data, flags});
destination.send(payload);
return this;
}
}
}
module.exports = WebSockServer;
//CLIENT CODE
function webSock(url) {
const ws = new WebSocket(url);
let events = {};
//Create an event handler
this.on = function on(event, callback) {
events[event] = {callback, once: false};
return this;
}
//Create an event handler for one time use
this.once = function once(event, callback) {
events[event] = {callback, once: true};
return this;
}
//Emit message to server
this.emit = function emit(event, data) {
let flags = {
binary: []
};
//Check for binary data
for (let key in data) {
if (Buffer.isBuffer(data[key])) {
const stringified = data[key].toJSON();
data[key] = stringified;
flags.binary.push(key);
}
}
const payload = JSON.stringify({event, data, flags});
ws.send(payload);
return this;
}
ws.on('open', () => {
if (events['open']) {
events['open'].callback(ws);
}
});
ws.on('close', () => {
if (events['close']) {
events['close'].callback();
}
})
ws.on('message', json => {
const message = JSON.parse(json);
//Check flags
for (let key in message.flags) {
if (key === 'binary' && message.flags[key].length > 0) {
message.flags[key].forEach(buffer => {
const parsed = Buffer.from(message.data[buffer]);
message.data[buffer] = parsed;
});
}
}
//Check if event handler exists & check if event is only to be triggered once
if (events[message.event] && !events[message.event].once) {
events[message.event].callback(message.data);
}
else if (events[message.event] && events[message.event].once) {
events[message.event].callback(message.data);
delete events[message.event];
}
else {
return;
}
});
}
module.exports = webSock;
Any help would be much appreciated, I'm sure I'm missing something obvious.

Ember includedCommands: HTTPS request does not fetch

I am writing an ember includedCommand for fetching and updating the app/index.html file - which uses NodeJS https and fs module to replace the indexFile by calling a function BuildIndexFile, where I am facing a weird issue -
When I perform command ember server --update-index - I can see the BuildIndexFile is being called and the https request is made to the remote server which downloads the file and gets written by fs.writeFileSync in app/index.html.
But when I perform ember update-index which is an included command, I can see BuildIndexFile has been called, and it reaches till console.log('Fetching index.html'); and I believe it is calling https.request... but it closes from there, I have no idea why the call didn't go through, when I debugged using node --inspect-brk ./node_modules/.bin/ember update-index I can see the https is available on the file, but not executing.
I am attaching my sample code available as a in-repo-addon available at lib/hello/index.js -
/* eslint-env node */
'use strict';
const parseArgs = require('minimist');
const watchman = require('fb-watchman');
let client = new watchman.Client();
client.capabilityCheck({optional: [], required: ['relative_root']}, function (error, response) {
if (error) {
console.log(error);
}
console.log('Watchman', response);
});
const ServeCommand = require('ember-cli/lib/commands/serve');
const ARGS = parseArgs(process.argv.slice(2));
const fs = require('fs');
const https = require('https');
module.exports = {
name: 'hello',
isDevelopingAddon() {
return true;
},
includedCommands: function() {
var self = this;
return {
hello: ServeCommand.extend({
name: 'hello',
description: 'A test command that says hello',
availableOptions: ServeCommand.prototype.availableOptions.concat([{
name: 'updateindex',
type: String
}]),
run: function(commandOptions, rawArgs) {
console.log(commandOptions, rawArgs);
if (commandOptions['updateindex']) {
console.log('Update Index')
}
const sampleHelloPromise = sampleHello();
const servePromise = this._super.run.apply(this, arguments);
return Promise.all([sampleHelloPromise, servePromise]);
}
}),
updateIndex: {
name: 'update-index',
description: 'Update Index File',
availableOptions: [{
name: 'index-file',
type: String
}],
run: function(commandOptions, rawArgs) {
BuildIndexFile(self.project.root, 'https://yahoo.com', {});
}
}
}
},
preBuild: function(result) {
let self = this;
if (ARGS['update-index']) {
BuildIndexFile(self.project.root, 'https://google.com', {}).then(function() {
delete ARGS['update-index'];
})
.catch(function(e) {
console.log(e);
});;
}
}
};
async function sampleHello() {
return await new Promise(resolve => {
setTimeout(() => resolve('hello'), 2000);
})
}
const BuildIndexFile = (rootPath, target, headers) => {
try {
debugger;
const indexFile = `${rootPath}/app/index.html`;
let noIndexFile = !fs.existsSync(indexFile);
return new Promise(function (resolve, reject) {
let options = {
hostname: target.replace(/^http(?:s):\/\//i, ''),
port: 443,
method: 'GET'
};
let dataContent = '';
console.log('Fetching index.html');
var request = https.request(options, function(response) {
response.on('data', function(d) {
dataContent += d;
});
response.on('end', function() {
fs.writeFileSync(indexFile, dataContent);
return resolve();
});
});
request.on('error', function(e) {
console.log(e);
return reject(`Error: Creating Index File`);
});
request.end();
});
} catch(e) {
throw e;
}
}

javascript classes call function

I am beginner in programming and I am trying the javascript classes, I want to call the boardCastinit function from the override function onConnMessage, but I am getting this error message, Please help in this issue.
boReferenceError: boardCastInit is not defined
websocket.js
class websocket extends webSocketModel {
constructor() {
let server = new Server();
let mongodb = new mongoDB();
super(server.server);
}
onConnMessage(message) {
let clients = this.clients;
boardCastInit(1);
}
boardCastInit(data){
console.log(data)
}
}
module.exports = websocket;
websocketModel.js
const ws = require('websocket').server;
class webSocketModel {
constructor(httpServer) {
if(!httpServer) throw 'Null Http Server';
this.websocket = new ws({ httpServer: httpServer, autoAcceptConnections: false });
this.websocket.on('request', this.onConnOpen.bind(this));
}
onConnOpen(request) {
var connection = request.accept('echo-protocol', request.origin);
console.log('Connection Accepted');
connection.on('message', this.onConnMessage);
connection.on('close', this.onConnClose);
}
onConnMessage(message) {
if (message.type === 'utf8') {
console.log(message.utf8Data);
} else if (message.type == 'binary') {
console.log(message.binaryData.length + 'bytes');
}
}
onConnClose(reasonCode, description) {
console.log('Connection Closed');
}
}
module.exports = webSocketModel;
just change boardCastInit(1) to this.boardCastInit(1)
onConnMessage(message) {
let clients = this.clients;
this.boardCastInit(1);
}
You should be calling it from the class this reference:
class websocket extends webSocketModel {
constructor() {
let server = new Server();
let mongodb = new mongoDB();
super(server.server);
}
onConnMessage(message) {
let clients = this.clients;
this.boardCastInit(1);
}
boardCastInit(data){
console.log(data)
}
}
module.exports = websocket;
You are missing this (should be this.boardCastInit(1)).
This could be a binding issue. Perhaps you want to use arrow function instead on your onConnMessage method:
onConnMessage = (message) => {
let clients = this.clients;
this.boardCastInit(1);
}
This will ensure that this refers to the websocket class which has the boardCastInit method defined.
Try binding the boardCastInit() function inside the constructor like this.
constructor() {
let server = new Server();
let mongodb = new mongoDB();
super(server.server);
this.boardCastInit = this.boardCastInit.bind(this);
}
Then call it from the this reference.
onConnMessage(message) {
let clients = this.clients;
this.boardCastInit(1);
}

Categories

Resources