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
});
Related
I have written a service to call another API service. But at times, when I call the service I get an error message. One such error is "Unbound Parameters found", but the status code what I get is 200. So, I hope 200 is not the correct status code here for this kind of error output.
How to get the correct status code for this case?
The method currently I use to get the Status code is response.statusCode
function apiCall(url, protocol) {
function externalApi(url, callback) {
try {
var https = $.require(protocol);
var request = https.request(url, function (response) {
var str = '';
var statusCode = response.statusCode;
var headers = response.headers;
response.on('data', function (data) {
str += data;
});
response.on('end', function () {
console.log("Data is " + str);
console.log("Status Code is " + statusCode);
console.log("Header is " + JSON.stringify(headers));
callback(str, statusCode);
});
});
request.on('error', function (e) {
console.log('Problem with request: ' + e.message);
console.log('Problem with request: ' + e);
});
request.end();
} catch (err) {
console.log("the error is" + err);
var errCode = err.statusCode;
callback(err, 999);
}
}
var status = function (data, statusCode) {
var callStatus = {};
if (statusCode == 200) {
callStatus.retrievedData = data;
callStatus.statusCode = statusCode;
callStatus.MESSAGE = "API successfully called";
} else if (statusCode == 999) {
callStatus.MESSAGE = "API call failed";
callStatus.errorDetails = data;
callStatus.errorDescription = "Error generated from Catch Block";
} else {
callStatus.details = data;
callStatus.statusCode = statusCode;
}
console.log(callStatus);
};
externalApi(url, status);
}
What i get is the error message, but status code as 200. But what would I need is error message with the exact error status code.
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
}
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 would like to replace the if(body.toString().indexOf("404") !== 0) block with some generic error handling code but I can't seem to see where it throws an error when the target host is down. So far, this is the only hacky method I've managed to put together that works.
app.get('/', function(req, res){
var sites = ["foo.com", "bar.com"];
var returnObj = [];
var index = 0;
getSites(index);
// Recursively add data from each site listed in "sites" array
function getSites(index) {
if(index < sites.length) {
var url = sites[index];
var _req = http.get({host: url}, function(_res) {
var bodyChunks = [];
_res.on('data', function(chunk) {
bodyChunks.push(chunk);
}).on('end', function() {
var body = Buffer.concat(bodyChunks);
if(body.toString().indexOf("404") !== 0) {
returnObj.push(JSON.parse(body));
}
getSites(++index);
});
});
_req.on('error', function(e) {
console.log('ERROR: ' + e.message);
});
} else {
res.json(returnObj);
res.end();
}
}
});
You can check the status code of the response.
if(_req.statusCode === 200) {
//Response okay.
}
Here's a list of the status codes.
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");