So I keep getting the following error with my code:
Reference Error: ws is not defined
My code is this:
config = require "./config.json"
chalk = require "chalk"
shortid = require "shortid"
maxplayers = config.maxplayers
WebSocketServer = require("ws").Server
wss = new WebSocketServer({port: config.port})
wss.on "connection", (ws) ->
console.log "Socket " + chalk.green("connected") + "."
ws.on "message", (msg) ->
console.log "Received packet: " + msg
return
console.log "Server " + chalk.cyan("started") + " on port " + config.port + "."
Why is this happening? CoffeeScript's Try page gives me exactly what I want. Why does NPM CoffeeScript not do it? If I do coffee -c myscriptname (yes I replaced myscriptname with my script name), it gives me this:
// Generated by CoffeeScript 1.9.1
(function() {
ws.on("message", function(msg) {
return console.log("Received packet: " + msg);
});
return;
}).call(this);
Related
The mentions I send to the incoming webhook renders as plain text.
Note: Sending post request using the request package.
Tried the following:
sending mentions as <#userid>
Result: <#userid> // as plain text
request.post(
`${channels[message.channel.name]}`,
{
json: {
text:
'To: ' + mapDiscordToSlackNames(message.mentions.users) + '\n' +
'Discord channel: #' + message.channel.name + '\n' +
'Link: <' + message.url + '|Link to post>' + '\n' +
Result: To: #soda // as plain text not as mention to #soda user
Entire Code
// require the discord.js module
const Discord = require('discord.js');
const devs = require('./devs.json');
const channels = require('./channels.json');
const dotenv = require('dotenv');
const path = require('path');
var request = require('request');
dotenv.load({
path: path.join(__dirname, `.env`),
silent: true
});
// create a new Discord client
const client = new Discord.Client();
// Map discord usernames of devs to slack usernames
function mapDiscordToSlackNames(discordUsers) {
return discordUsers.map( user => {
return '#' + devs[user.username];
})
}
// when the client is ready, run this code
// this event will only trigger one time after logging in
client.once('ready', () => {
console.log('Discord Connected!');
});
// on message on discord
client.on('message', message => {
console.log(channels[message.channel.name]);
request.post(
`${channels[message.channel.name]}`,
{
json: {
text:
'To: ' + mapDiscordToSlackNames(message.mentions.users) + '\n' +
'Discord channel: #' + message.channel.name + '\n' +
'Link: <' + message.url + '|Link to post>' + '\n' +
'Original Message: \n' +
'\t"' + message.author.username + ': ' + message.cleanContent + '"\n' +
`Attachements: ${message.attachments.map(attachment => attachment.url)}`
},
},
function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body);
}
}
);
});
// login to Discord with app's token
client.login(process.env.DISCORD_TOKEN);
devs is a json object which has returns slack usernames corresponding to discord usernames.
Turns out I was sending userid by escaping '<' & '>' in string like
'<#userid>' and so it was passing as plain text.
To mention someone in slack do 'To: <#' + userid + '>'
The userid starts with U and can be found after the team/ in url of
your workspace eg: Cxxxxx/team/Uxxxxx/
Similar to this question,
I have a script that downloads a file to a given url via http.get.
How can I make sure the pipe is finished before continuing to the next iteration with just the http/https module??
//nodejs default libs
var fs = require("fs");
var http = require('https');
function dlFile(fullFilePath, dlUrl, fsize, fname){
var file = fs.createWriteStream(fullFilePath); //fullFilePath will dictate where we will save the file + filename.
var rsult ='';
var downloadedFsize;
var stats; //stats of the file will be included here
var request = http.get( dlUrl, function(response) {
let rsult = response.statusCode;
//will respond with a 200 if the file is present
//404 if file is missing
response.pipe(file);
/*pipe writes the file...
how do we stop the iteration while it is not yet finished writing?
*/
console.log(" \n FILE : " + fname);
console.log("File analysis finished : statusCode: " + rsult + " || Saved on " + fullFilePath);
console.log(' \n Downloaded from :' + dlUrl);
console.log(' \n SQL File size is : ' + fsize);
//identify filesize
stats = fs.statSync(fullFilePath);
downloadedFsize = stats["size"]; //0 because the pipe isn't finished yet...
console.log(' actual file size is : ' + downloadedFsize);
}).on('error', function(e) {
console.error(e);
//log that an error happened to the file
}).on('end', function(e){
//tried putting the above script here but nothing happens
});
return rsult;
}
Is there a cleaner approach similar to what I have in mind above? or should I approach this differently? I tried putting the code on .on('end' but it does nothing
The end event is not triggered on the request, instead it is triggered on the response (docs):
response.on("end", function() {
console.log("done");
});
As #Jonas Wilms says, the trigger was indeed on response.
//nodejs default libs
var fs = require("fs");
var http = require('https');
function dlFile(fullFilePath, dlUrl, fsize, fname){
var file = fs.createWriteStream(fullFilePath); //fullFilePath will dictate where we will save the file + filename.
var rsult ='';
var downloadedFsize;
var stats; //stats of the file will be included here
var request = http.get( dlUrl, function(response) {
let rsult = response.statusCode;
//will respond with a 200 if the file is present
//404 if file is missing
response.pipe(file).on('finish', function(e){
console.log(" \n FILE : " + fname);
console.log("File analysis finished : statusCode: " + rsult + " || Saved on " + fullFilePath);
console.log(' \n Downloaded from :' + dlUrl);
console.log(' \n SQL File size is : ' + fsize);
//identify filesize
stats = fs.statSync(fullFilePath);
downloadedFsize = stats["size"];
console.log(' actual file size is : ' + downloadedFsize);
});
/*pipe writes the file above, and output the results once it's done */
}).on('error', function(e) {
console.error(e);
//log that an error happened to the file
}).on('end', function(e){
//tried putting the above script here but nothing happens
});
return rsult;
}
I have a class which is being used to connect to a device. I have made in instance of the class in my application
app.js
myConn = new myConnection();
myConnection.js
function myConnection(){
this.settings = {
host: '192.168.225.195',
port: 22,
username: 'sysadmin',
password: 'pass'
};
}
I have a function within said class that executes a command on the remote device but that requires a password. When this happens stderr.on is executued and I send the password and a newline char.
myConnection.prototype.installPatch = function(callback){
this.conn.exec('sudo -S bash /tmp/update.sh', function(err, stream){
var standardMsgs = '';
var errorMsgs = '';
if(err) throw err;
stream.on('close', function(code, signal) {
callback(standardMsgs, errorMsgs);
}).on('data', function(data) {
standardMsgs += "<br>" + data;
console.log('STDOUT: ' + data);
}).stderr.on('data', function(data) {
errorMsgs += data;
console.log('STDERR: ' + data);
stream.write(myConn.conn.config.password + '\n');
});
});
}
While this works I am not a fan of accessing the password with
stream.write(myConn.conn.config.password + '\n');
since a change to the name "myConn" in app.js would required the same change in the "installPatch" function.
I had intended to use
stream.write(this.settings.password + '\n');
Do I have any other options that will allow me to retrieve the password from within the myConnection class? I hope I am just overlooking the obvious.
Ok, so I believe it was starring me in the face.
Change
stream.write(myConn.conn.config.password + '\n');
to
stream.write(stream._client.config.password + '\n');
Can we modify fs.readFileSync(__dirname + '/game.php'); to fs.readFileSync(__dirname + '/game.php?id='+id); ?
It gives me an error:
fs.js:549 return binding.open(pathModule._makeLong(path), stringToFlags(flags), mode);
Is there any other way?
I suppose you're trying to do a GET call to your php service, which runs on its own (like you have a webserver which provides php pages on localhost/game.php or similar).
If this is the case, you need to use the http library, and I think something like this can work for you:
"use strict";
var http = require("http");
var id = 123;
var options = {
host: "localhost",
port: 80,
path: 'game.php?id=' + id,
method: "GET"
};
var req = http.request(options, function(res) {
console.log("STATUS: " + res.statusCode);
console.log("HEADERS: " + JSON.stringify(res.headers));
res.on("data", function (chunk) {
console.log("BODY: " + chunk);
});
});
req.end();
I have a large complex web app with thousands of lines of Javascript. There is a small set of intermittent Javascript bugs that are report by users.
I think these are epiphenomena of race conditions - something has not initialised correctly and the Javascript crashes causing 'down stream' js not to run.
Is there anyway to get Javascript execution crashes to log back server side?
All the js logging libraries like Blackbird and Log4JavaScript are client-side only.
I have written a remote error logging function using window.onerror as suggested by #pimvdb
Err = {};
Err.Remoterr = {};
Err.Remoterr.onerror = function (msg, errorfileurl, lineno) {
var jsonstring, response, pageurl, cookies;
// Get some user input
response = prompt("There has been an error. " +
"It has been logged and will be investigated.",
"Put in comments (and e-mail or phone number for" +
" response.)");
// get some context of where and how the error occured
// to make debugging easier
pageurl = window.location.href;
cookies = document.cookie;
// Make the json message we are going to post
// Could use JSON.stringify() here if you are sure that
// JSON will have run when the error occurs
// http://www.JSON.org/js.html
jsonstring = "{\"set\": {\"jserr\": " +
"{\"msg\": \"" + msg + "\", " +
"\"errorfileurl\": \"" + errorfileurl + "\", " +
"\"pageurl\": \"" + pageurl + "\", " +
"\"cookies\": \"" + cookies + "\", " +
"\"lineno\": \"" + lineno + "\", " +
"\"response\": \"" + response + "\"}}}";
// Use the jquery cross-browser post
// http://api.jquery.com/jQuery.post/
// this assumes that no errors happen before jquery has initialised
$.post("?jserr", jsonstring, null, "json");
// I don't want the page to 'pretend' to work
// so I am going to return 'false' here
// Returning 'true' will clear the error in the browser
return false;
};
window.onerror = Err.Remoterr.onerror;
I deploy this between the head and body tags of the webpage.
You will want to change the JSON and the URL that you post it to depending on how you are going to log the data server side.
Take a look at https://log4sure.com (disclosure: I created it) - but it is really useful, check it out and decide for yourself. It allows you to log errors/event and also lets you create your custom log table. It also allows you to monitor your logs real-time. And the best part, its free.
You can also use bower to install it, use bower install log4sure
The set up code is really easy too:
// setup
var _logServer;
(function() {
var ls = document.createElement('script');
ls.type = 'text/javascript';
ls.async = true;
ls.src = 'https://log4sure.com/ScriptsExt/log4sure.min.js';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(ls, s);
ls.onload = function() {
// use your token here.
_logServer = new LogServer("use-your-token-here");
};
})();
// example for logging text
_logServer.logText("your log message goes here.")
//example for logging error
divide = function(numerator, divisor) {
try {
if (parseFloat(value) && parseFloat(divisor)) {
throw new TypeError("Invalid input", "myfile.js", 12, {
value: value,
divisor: divisor
});
} else {
if (divisor == 0) {
throw new RangeError("Divide by 0", "myfile.js", 15, {
value: value,
divisor: divisor
});
}
}
} catch (e) {
_logServer.logError(e.name, e.message, e.stack);
}
}
// another use of logError in window.onerror
// must be careful with window.onerror as you might be overwriting some one else's window.onerror functionality
// also someone else can overwrite window.onerror.
window.onerror = function(msg, url, line, column, err) {
// may want to check if url belongs to your javascript file
var data = {
url: url,
line: line,
column: column,
}
_logServer.logError(err.name, err.message, err.stack, data);
};
// example for custom logs
var foo = "some variable value";
var bar = "another variable value";
var flag = "false";
var temp = "yet another variable value";
_logServer.log(foo, bar, flag, temp);