Running a node server and I am getting the following error.
SyntaxError: Unexpected end of input
var http = require('http');
var socketio = require('socket.io');
if (typeof String.prototype.startsWith != 'function') {
String.prototype.startsWith = function (str){
return this.slice(0, str.length) == str;
};
}
function log_me(msg){
var ts = new Date(new Date().getTime() - (3600000*4));
var tss = ts.toString();
tss = tss.substring(0, tss.indexOf(' GMT'));
console.log(tss + ": " + msg);
}
var app = http.createServer(function(req, res) {
var postData = "";
req.on('data', function(chunk) {
postData += chunk; //Get the POST data
});
req.on('end', function() {
if (typeof(postData) !== "undefined") {
var message = JSON.parse(postData); <-- Here is the issue line 25
//Do something here
//Todo...
}
});
res.end();
}).listen(8080); //Use a non-standard port so it doesn't override your Apache
var io = socketio.listen(app);
//var io = require('socket.io').listen(8080,'0.0.0.0');
io.set('log level', 2);
// io.set('transports', ['flashsocket', 'polling', 'websocket']);
io.set('origins', '*:*');
You can use something like that:
JSON.safeParse = function(data) {
try {
return JSON.parse(data);
} catch (e) {
return false;
}
}
Change your JSON.parse call to JSON.safeParse, and then check if the result is valid:
var message = JSON.safeParse(postData);
if (message) {
// valid!
} else {
// invalid
}
Related
This error appears constantly after running the code.enter code here.the fifth day I sit and do not understand what the problem is.if anyone understands this topic, please help.
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
"use strict";
var config = require('config');
var chalk = require('chalk');
var logError = chalk.red;
var logSuccess = chalk.green;
function padHexStr(strval, length){
var byteLength = length;
if(length === undefined || length === null || length === 0){
byteLength = 32;
}
var pad = "00".repeat(byteLength);
if(strval.substring(0,2) === "0x"){
var trunStrVal = strval.substring(2,strval.length);
return padHexStr(trunStrVal, length);
}
else{
return "0x"+pad.substring(0,pad.length-strval.length)+strval;
}
}
module.exports = {
webServer : null,
webServerPort : 8080,
webSocketIo : null,
webSocket: null,
initWebsocket: function(httpServer, done){
var self = this;
self.webSocketIo = require('socket.io');
self.webSocket = self.webSocketIo.listen(httpServer);
self.webSocket.on('connection', function(client){
var clientAddress = client.request.connection.remoteAddress;
var clientPort = client.request.connection.remotePort;
console.log('client connected from ' + clientAddress + ':' + clientPort);
});
done();
},
init : function(expressApp,done){
var self = this;
self.webServer = require("http").createServer(expressApp);
console.log('activating web server');
if(config.has('webserver.port')){
self.webServerPort = config.get('webserver.port');
}
require('./webtemplate')(expressApp);
require('./webstatic')(expressApp);
self.webServer.listen(self.webServerPort, function(err){
if(err){
logError(err);
return;
}
console.log(logSuccess("server listening on port: "+self.webServerPort));
self.initWebsocket(self.webServer,done);
});
}
};
My Code
I want to make a multiple connection to a telnet console. This project is for Teamspeak and Teamspeak just communicate with telnet. I´ve a object that create a telnet connection as socket with the net lib. If we have just one instance to connect all works fine and I get the serverlist over the telnet connection back. But if I´ve two instance he says invalid loginname or password. That login informations are correct and he also try just to connect to one server.
My Class:
/*
Teamspeak query client class
#instance: Instance object of the teamspeak query client
*/
function TeamspeakQueryClient(instance) {
events.EventEmitter.call(this);
var $this = this,
socket = net.connect(instance.port, instance.ip),
reader = null,
skipLines = -2,
queue = [ ],
executing = null,
server = null;
this.Type = 'Unknown';
this.Id = null;
this.Connected = false;
this.Banned = false;
/*
Socket settings
*/
socket.setKeepAlive(true, 60000);
/*
Socket connect to the teamspeak instance
*/
socket.on("connect", function() {
reader = LineInputStream(socket);
reader.on("line", function(line) {
var s = line.trim();
console.log(line);
// Skipp the first lines
if(skipLines < 0){
if(line === 'TS3') {
this.Type = 'Teamspeak';
};
skipLines++;
if(skipLines === 0) {
checkQueue();
if(server === null) {
$this.SendCommand("login", {client_login_name: instance.client, client_login_password: instance.password}, function(err, response, rawResponse) {
console.log(err);
if(err === null) {
if(err.id === 3329) {
$this.Banned = true;
};
$this.CloseSocket();
} else {
$this.SendCommand("serverlist", null, function(err, response, rawResponse){
console.log(response);
if(response[0] === undefined) {
console.log('1 server');
} else {
console.log('mehrere server');
};
//console.log(rawResponse);
/*cl.send("clientlist", function(err, response, rawResponse){
console.log(util.inspect(response));
});*/
});
};
});
} else {
console.log(server);
};
};
return;
};
// Parse server request
var response = undefined;
if(s.indexOf("error") === 0){
response = parseResponse(s.substr("error ".length).trim());
executing.error = response;
if(executing.error.id === 0) delete executing.error;
if(executing.cb) executing.cb.call(executing, executing.error, executing.response,
executing.rawResponse);
executing = null;
checkQueue();
} else if(s.indexOf("notify") === 0){
s = s.substr("notify".length);
response = parseResponse(s);
$this.emit(s.substr(0, s.indexOf(" ")), response);
} else if(executing) {
response = parseResponse(s);
executing.rawResponse = s;
executing.response = response;
};
});
$this.emit("connect");
});
/*
Socket error
*/
socket.on("error", function(err){
log.LogLine(1, 'TeamspeakQueryClient: We got a error');
log.LogLine(1, 'Message: '+err);
$this.emit("error", err);
});
/*
Socket close
*/
socket.on("close", function(){
log.LogLine(3, 'TeamspeakQueryClient: Socket from '+instance.alias+' closeing...');
$this.emit("close", queue);
});
/*
Function to send a custom command to the telnet console
*/
TeamspeakQueryClient.prototype.SendCommand = function SendCommand() {
var args = Array.prototype.slice.call(arguments);
//console.log(args);
var options = [], params = {};
var callback = undefined;
var cmd = args.shift();
args.forEach(function(v){
if(util.isArray(v)){
options = v;
} else if(typeof v === "function"){
callback = v;
} else {
params = v;
}
});
var tosend = tsescape(cmd);
options.forEach(function(v){
tosend += " -" + tsescape(v);
});
for(var k in params){
var v = params[k];
if(util.isArray(v)){ // Multiple values for the same key - concatenate all
var doptions = v.map(function(val){
return tsescape(k) + "=" + tsescape(val);
});
tosend += " " + doptions.join("|");
} else {
tosend += " " + tsescape(k.toString()) + "=" + tsescape(v.toString());
}
}
queue.push({cmd: cmd, options: options, parameters: params, text: tosend, cb: callback});
if(skipLines === 0) checkQueue();
};
/*
Function to close the socket
*/
TeamspeakQueryClient.prototype.CloseSocket = function CloseSocket() {
socket.destroy();
$this.emit("close");
};
/*
Function to parse a string to a object
#s: String of the object that will be parsed
#return: Object of the parsed string
*/
function parseResponse(s){
var response = [];
var records = s.split("|");
response = records.map(function(k){
var args = k.split(" ");
var thisrec = { };
args.forEach(function(v) {
if(v.indexOf("=") > -1) {
var key = tsunescape(v.substr(0, v.indexOf("=")));
var value = tsunescape(v.substr(v.indexOf("=")+1));
if(parseInt(value, 10) == value) value = parseInt(value, 10);
thisrec[key] = value;
} else {
thisrec[v] = "";
};
});
return thisrec;
});
if(response.length === 0) {
response = null;
} else if(response.length === 1) {
response = response.shift();
};
return response;
};
/*
Function to write commands into the socket
*/
function checkQueue() {
if(!executing && queue.length >= 1){
executing = queue.shift();
socket.write(executing.text + "\n");
};
};
/*
Function to escape a telnet string
#s: String that want to be escaped
#return: The escaped string
*/
function tsescape(s) {
return s
.replace(/\\/g, "\\\\")
.replace(/\//g, "\\/")
.replace(/\|/g, "\\p")
.replace(/\n/g, "\\n")
.replace(/\r/g, "\\r")
.replace(/\t/g, "\\t")
.replace(/\v/g, "\\v")
.replace(/\f/g, "\\f")
.replace(/ /g, "\\s");
};
/*
Function to unescape a telnet string
#s: String that want to be unescaped
#return: The unescaped string
*/
function tsunescape(s) {
return s
.replace(/\\s/g, " ")
.replace(/\\p/g, "|")
.replace(/\\n/g, "\n")
.replace(/\\f/g, "\f")
.replace(/\\r/g, "\r")
.replace(/\\t/g, "\t")
.replace(/\\v/g, "\v")
.replace(/\\\//g, "\/")
.replace(/\\\\/g, "\\");
};
};
util.inherits(TeamspeakQueryClient, events.EventEmitter);
How I open the class
if I call example one all works fine but example two has the descriped error.
Example 1:
test1 = new TeamspeakQueryClient({
"alias": "First-Coder Testinsance",
"ip": "first-coder.de",
"port": 10011,
"client": "serveradmin",
"password": "SECURE"
});
Example 2:
test1 = new TeamspeakQueryClient({
"alias": "First Insance",
"ip": "HIDDEN",
"port": HIDDEN,
"client": "serveradmin",
"password": "SECURE"
});
test2 = new TeamspeakQueryClient({
"alias": "Second Instance",
"ip": "HIDDEN",
"port": HIDDEN,
"client": "serveradmin",
"password": "SECURE"
});
Screenshots
Picture of the error in the console
According to your error, your second instance is not sending the correct login:
error id=520 msg=invalid\sloginname\sor\spassword
The additional errors displayed are due to your code not handling errors correctly.
For example:
socket.on("connect", function() {
...
if(err === null) {
if(err.id === 3329) {
If err === null, why would err have an element id?
Most likely this is code error, and you actually meant err !== null
$this.SendCommand("serverlist", null, function(err, response, rawResponse){
console.log(response);
if(response[0] === undefined) {
This error triggers because the (above) previous error was not caught.
At this point, the client is not logged in (authorized).
So when the serverlist command is sent, it riggers another error.
This additional error is also no handled, instead response is immediately used.
I am a newbie and trying to create an application based on poloniex.js API getting error-TypeError: curl.setopt is not a function] set node-curl(not working) and node-libcurl (partially works,but the function seems incorrectly expressed) slightly confused between the two curl) node-curl is outdated and maybe that's the problem-can you tell what is wrong?
'use strict';
var autobahn = require('autobahn'),
crypto = require('crypto'),
async = require('async'),
https = require('https'),
nonce = require('nonce')(),
querystring = require('querystring'),
Curl = require('node-libcurl').Curl,
microtime = require('microtime'),
events = require('events'),
util = require('util');
var Poloniex = function Poloniex() {};
Poloniex._query_tradeApi = function (req, callback) {
var post_data,
hash = crypto.createHmac('sha512', "key-key-key"),
sign,
received,
headers;
nonce = (new Date()).getTime() * 1000;
post_data = querystring.stringify(req);
hash.update(post_data);
sign = hash.digest("hex");
try {
headers = [ 'Key: ' + "SECRET-SECRET-SECRET", 'Sign: ' + sign ];
var curl = new Curl(),
close = curl.close.bind( curl );
curl.setopt('URL', 'https://poloniex.com/tradingApi/');
curl.setopt('POST', 1);
curl.setopt('POSTFIELDS', post_data);
curl.setopt('HTTPHEADER', headers);
received = '';
curl.on('data', function (chunk) {
received += chunk;
return chunk.length;
});
curl.on('header', function (chunk) {
return chunk.length;
});
curl.on('error', curl.close.bind( curl ),function (e) {
console.error('exchanges/poloniex', '_query_tradeApi', e,
req, e.stack);
callback(e, undefined);
curl.perform();
curl.close();
});
curl.on('end', function () {
try {
var data = JSON.parse(received);
callback(undefined, data);
} catch (ex) {
console.error('exchanges/poloniex', '_query_tradeApi',
ex, req, ex.stack);
callback(ex, received);
}
curl.close();
});
curl.perform();
} catch (ee) {
console.error('exchanges/poloniex', '_query_tradeApi', ee,
req, ee.stack);
callback(ee, received);
}
};
The syntax required is curl.setOpt, not curl.setopt.
I am trying to parse a field of return JSON data, from an API which has a lot of strange characters in it (East Asian Symbols, curly quotes etc.). I am getting this error and do not know how to fix it. Is there a way to convert the request response to some format that "escapes" the bad text.
Here is the error:
Here is my exact code, I am sorry it is so long.
var fs = require('fs'),
http = require('http'),
request = require('request');
var url = 'http://app.sportstream.com/api/tagstream/tagStreamForStageTwoModeration?q={%22customerId%22:%22ABHoko14%22,%22type%22:{%22$in%22:[%22image%22,%22video%22]}}&_=_5555'
var firstTime = false
var m = 1
function get() {
console.log('ghghg')
http.get(url, function(res) {
var body = '';
res.on('data', function(chunk) {
body += chunk;
});
res.on('end', function() {
body = JSON.parse(body)
jParse(body)
setTimeout(get, 5000)
});
}).on('error', function(e) {
console.log("Got error: ", e);
setTimeout(get, 5000)
});
}
function jParse(info) {
//data = JSON.parse(info)
data = info
entries = data.entries
if (firstTime) {
numEntries = 800 //entries.length
firstTime = false
} else {
numEntries = 2
//numEntries = entries.length - numEntries
if (numEntries) {
for (i = 0; i < numEntries; i++) {
type = entries[i]['type']
title = entries[i]['author']
if (type == 'video') {
url = entries[i]['ssMetaData']['videos']['standard_resolution']['url']
download(url, 'images/aFile.mp4', function() {
console.log('hello')
})
} else if (type == 'image') {
url = entries[i]['ssMetaData']['images']['standard_resolution']['url']
download(url, 'images/' + m + 'File.jpg', function() {
console.log('hello')
})
} else {
console.log('no data')
}
m++
}
}
}
}
get()
And here is my error
undefined:1
����
^
SyntaxError: Unexpected token �
at Object.parse (native)
By foreign characters; I assume you are referring to UTF-8 encoded string.
Why don't you try setting the Content-Type encoding on the response like this:
http.get(url, function(res) {
res.header("Content-Type", "application/json; charset=utf-8");
How would I handle a situation where the file does not exist on the server, or is unable to connect with the server to get the file?
As of the code below, the file download still occurs, and the file is empty.
var https = require('https');
var fs = require('fs');
var exec = require('child_process').exec;
var file = fs.createWriteStream('mediaserver_setup.exe');
var len = 0;
var req = https.get(url + 'appdata/update_setup.exe', function (res) {
if (res.statusCode === 404) {
alert('problem with request:');
}
res.on('data', function (chunk) {
file.write(chunk);
len += chunk.length;
var percent = (len / res.headers['content-length']) * 100;
progressLoading.val(percent);
});
res.on('end', function () {
setTimeout(function () {
file.close();
}, 500);
});
file.on('close', function () {
win.close();
exec('update_setup.exe');
});
});
req.on('error', function (err) {
alert('problem with request: ');
});
Use the error event for requests, or check the status code of the response:
var https = require('https');
var req = https.get(options, function(res) {
// use res.statusCode
if (res.statusCode === 404) {
// example for checking 404 errors
}
});
req.on('error', function(err) {
// an error has occurred
});