How to parse a json file with nodejs - node.js

I got a little problem with the nodejs fetch module and more particularly with the JSON parse. When I want to parse the stock variable, he tells me that the size is equal to 0 ? But my file is not empty and the path is good.
The code is really simple but I don't know why this error append and I spend too much time on this.
Someone know why I get this error and how I can resolve it ?
here the code of my js file :
const fetch = require('node-fetch');
const keyword='test';
const url='http://localhost:8888/test.json';
fetch(url).then((stock) => {
console.log(stock);
const jsonFile = JSON.parse(stock);
const newCategory = jsonFile[test];
console.log(newCategory);
}).catch((e)=>{console.log(e)});
And the error in my terminal with the first console.log() :
Response {
size: 0,
timeout: 0,
[Symbol(Body internals)]:
{ body:
PassThrough {
_readableState: [ReadableState],
readable: true,
_events: [Object],
_eventsCount: 2,
_maxListeners: undefined,
_writableState: [WritableState],
writable: false,
allowHalfOpen: true,
_transformState: [Object] },
disturbed: false,
error: null },
[Symbol(Response internals)]:
{ url: 'http://localhost:8888/test.json',
status: 200,
statusText: 'OK',
headers: Headers { [Symbol(map)]: [Object] },
counter: 0 } }
SyntaxError: Unexpected token o in JSON at position 1
at JSON.parse (<anonymous>)
at fetch.then (/Users/me/Desktop/test_json/index.js:11:30)
at process._tickCallback (internal/process/next_tick.js:68:7)

The fetch api returns a Body object
you can call Body.json()
Using async/await:
const body = await fetch(url);
const json = await body.json();
console.log(json);
Using promises:
fetch(url).then((stock) => {
return stock.json()
}).then(json => {
console.log(json);
});
JSON.parse:
fetch(url).then((stock) => {
return stock.text()
}).then(text => {
console.log(JSON.parse(text));
});

You need to pass the body in json parse like bellow,
JSON.parse(stock.text())
Or you can directly use json data without parsing just using stock.json() function

Related

Axios request working fine by itself but when I try to integrate it with my discord bot it always returns an error?

const { SlashCommandBuilder } = require("#discordjs/builders");
const axios = require("axios")
const { XRapidAPIKey, XRapidAPIHost} = require("../config.json");
module.exports = {
data: new SlashCommandBuilder()
.setName('stock')
.setDescription('Replies with the name of the stock and its current price.')
.addStringOption(option =>
option.setName('ticker')
.setDescription('The stock you want the price of.')
.setRequired(true)),
async execute(interaction) {
const ticker = interaction.options.getString('ticker');
const options = {
method: 'GET',
url: `https://realstonks.p.rapidapi.com/${ticker.toUpperCase()}`,
headers: {
"X-RapidAPI-Key": XRapidAPIKey,
"X-RapidAPI-Host": XRapidAPIHost
}
};
axios.request(options).then(function(response) {
interaction.reply(response.data);
}).catch(function(error) {
console.log(error);
});
}
this is the code for the stock price command but it does not work due to an error being thrown. It should send a message in my discord server with the json data from the axios request. It at first didn't work because I tried to put it in a function and return it but I realized that it needs to be in the command function but I cannot figure out why the request is returning a http 400 code even though it works fine by itself.
DiscordAPIError: Cannot send an empty message
at RequestHandler.execute (/Users/lukepitstick/personal/js/stocktrader/node_modules/discord.js/src/rest/RequestHandler.js:350:13)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at async RequestHandler.push (/Users/lukepitstick/personal/js/stocktrader/node_modules/discord.js/src/rest/RequestHandler.js:51:14)
at async CommandInteraction.reply (/Users/lukepitstick/personal/js/stocktrader/node_modules/discord.js/src/structures/interfaces/InteractionResponses.js:103:5) {
method: 'post',
path: '/interactions/986055380461301820/aW50ZXJhY3Rpb246OTg2MDU1MzgwNDYxMzAxODIwOnY5c1QzbDdIWVN0NW4zY2d4ODd6M2RRSHA1OVpORHZ5SmFXUkNyY0pKZDNpNGNyVjFtQzZ5UjFYck96ZHhJUVlVNjJ6YWNHRTBFbFBSczlWWXBTdHk2YzFuNFJrRFU5R3R3dDAyQ3ByRmtiaTBpRm1NYUVyRXVHYjhsUk84T25t/callback',
code: 50006,
httpStatus: 400,
requestData: {
json: {
type: 4,
data: {
content: undefined,
tts: false,
nonce: undefined,
embeds: undefined,
components: undefined,
username: undefined,
avatar_url: undefined,
allowed_mentions: undefined,
flags: undefined,
message_reference: undefined,
attachments: undefined,
sticker_ids: undefined
}
},
files: []
}
}
But when I run the code in its own file without the discord related stuff and console.log the data it outputs the json data as you would expect.

Not able to upload xlsx or csv file to azure blob storage

Want to upload XLSX or CSV file to azure. So I have created an API
http://localhost:3000/upload
Post Request using post man
This the code
app.post('/upload',(req,res)=>{
var form = new formidable.IncomingForm();
form.parse(req, async(err,fields,files)=> {
const blobServiceClient = await BlobServiceClient.fromConnectionString(AZURE_STORAGE_CONNECTION_STRING);
const containerClient = await blobServiceClient.getContainerClient('mycon');
if(!containerClient.exists()){
const createContainerResponse = await containerClient.create();
}
const blobName = files.file.name;
const blockBlobClient = containerClient.getBlockBlobClient(blobName);
const uploadBlobResponse = await blockBlobClient.upload(files,files.file.size);
console.log(files);
res.send({message:files.file.size + "uploaded"})
})
})
When I did console.log(files) in above code snippet
{
file: File {
_events: [Object: null prototype] {},
_eventsCount: 0,
_maxListeners: undefined,
size: 18,
path: 'C:\\Users\\bakhil\\AppData\\Local\\Temp\\upload_8531745c7d9ae14f105d50c775256e00',
name: 'Book1.csv',
type: 'application/vnd.ms-excel',
hash: null,
lastModifiedDate: 2020-04-01T10:03:55.885Z,
_writeStream: WriteStream {
_writableState: [WritableState],
writable: false,
_events: [Object: null prototype] {},
_eventsCount: 0,
_maxListeners: undefined,
path: 'C:\\Users\\bakhil\\AppData\\Local\\Temp\\upload_8531745c7d9ae14f105d50c775256e00',
fd: null,
flags: 'w',
mode: 438,
start: undefined,
autoClose: true,
pos: undefined,
bytesWritten: 18,
closed: false
}
}
}
When I am triggering the endpoint from Postman, facing the following issue:
UnhandledPromiseRejectionWarning: Error: body must be a string, Blob, ArrayBuffer, ArrayBufferView, or a function returning NodeJS.ReadableStream.
I have no clue about the error. Please help me to resolve it.
Thanks in advance.
Please try by changing the following line of code:
const uploadBlobResponse = await blockBlobClient.upload(files,files.file.size);
to
const uploadBlobResponse = await blockBlobClient.uploadFile(files.file.path);

Skype Interview API throws JSON Parsing error, when provided position code in payload

Sadly this question is not relevant anymore, since Microsoft decided to retire the api Read the details here
I am trying to implement skype interview api, when I provide payload to it, it throws JSON parsing error. If I provide an empty payload it works fine. When i provide any other payload mentioned here, it works. But as soon as I provide position code as mentioned in the above link it fails. Here is the code I am using -
exports.getLink = (req, res) => {
let payload = {
"code": "RENE2010"
}
, stringifyPayload = JSON.stringify(payload)
let token = generateToken(stringifyPayload)
fetch(config.skype.url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + token
},
body: stringifyPayload
})
.then(result => result.json())
.then(jsonResult => {
utils.sendResponse(res, jsonResult)
}, err => {
utils.sendResponse(res, null, 400, 'ERROR', err)
}).catch(ex => {
utils.sendResponse(res, null, 400, 'Exception', ex)
})
}
And here is the generateToken Method -
let generateToken = (content) => {
let token = jwt.sign({
jti: Guid.raw(),
iat: new Date().getTime(),
iss: config.skype.api_key,
sub: sha256(content),
exp: Math.floor(Date.now() / 1000) + 10
}, config.skype.app_secret)
return token
}
And here is the error which I am getting -
UnhandledPromiseRejectionWarning: FetchError: invalid json response body at https://interviews.skype.com/api/interviews reason: Unexpected token I in JSON at position 0
at /Users/xxx/node_modules/node-fetch/lib/index.js:272:32
at process._tickCallback (internal/process/next_tick.js:68:7)
(node:9550) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 2)
(node:9550) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
if I try to print the result without parsing into json this is the error I get -
{
size: 0,
timeout: 0,
[Symbol(Body internals)]:
{ body:
PassThrough {
_readableState: [ReadableState],
readable: true,
domain: null,
_events: [Object],
_eventsCount: 2,
_maxListeners: undefined,
_writableState: [WritableState],
writable: false,
allowHalfOpen: true,
_transformState: [Object] },
disturbed: false,
error: null },
[Symbol(Response internals)]:
{ url: 'https://interviews.skype.com/api/interviews',
status: 400,
statusText: 'Bad Request',
headers: Headers { [Symbol(map)]: [Object] },
counter: 0 } }
{ FetchError: invalid json response body at https://interviews.skype.com/api/interviews reason: Unexpected token I in JSON at position 0
at /Users/xxx/node_modules/node-fetch/lib/index.js:272:32
at process._tickCallback (internal/process/next_tick.js:68:7)
message:
'invalid json response body at https://interviews.skype.com/api/interviews reason: Unexpected token I in JSON at position 0',
type: 'invalid-json' }

Aerospike Query Error

query = CLIENT.query(NAMESPACE, SET);
stream = query.foreach();
/*
Get list of all avialable keys
*/
stream.on('error', (error) => {
throw error;
});
stream.on('data', (record) => {
console.info('data', record);
console.info('key', record.key.key);
});
stream.on('end', () => {
console.log('done!');
process.exit(0);
});
Receiving error - AerospikeError: Record does not exist in database. May be returned by read, or write with policy Aerospike.policy.exists.UPDATE.
error encountered in promise chain => { [AerospikeError: Record does not exist in database. May be returned by read, or write with policy Aerospike.policy.exists.UPDATE]
name: 'AerospikeError',
code: 2,
command:
QueryCommand {
client:
Client {
domain: null,
_events: {},
_eventsCount: 0,
_maxListeners: undefined,
config: [Object],
as_client: AerospikeClient {},
connected: true,
captureStackTraces: false },
args: [ 'sms_data', 'some_set', [Object], undefined ],
captureStackTraces: false,
key: undefined,
stream:
RecordStream {
aborted: false,
client: [Object],
_events: [Object],
_eventsCount: 3 } },
func: 'as_query_parse_records_async',
file: 'src/main/aerospike/aerospike_query.c',
line: 237,
inDoubt: false }
Although the data is present in the namespace and set.
query result :
aql> select * from sms_data.some_set;
+-----------------------------------------------------+----------+
| 0 | name |
+-----------------------------------------------------+----------+
| MAP('{"dummy":[{"x":"dgjasgdj"}], "name":"Vidur"}') | "Khanna" |
+-----------------------------------------------------+----------+
This is a bug in the Aerospike Node.js client (all versions up to and including v3.2.0). The short version is, that this occurs on Query operations, if at least one server node in the cluster does not have any records in the set that you are querying. See issue #253 on GitHub for details. This should get resolved in the next client release.

node-soap - Proper method of calling function

I know absolutely nothing about SOAP lol, But a vital part of my software requires I use it for a particular webservice. The documentation for the webservice was written for .net so it makes it even harder for me to understand what I need to do here. On top of all that they require authentication.
For the connecting I do not need to authorize so I am able to retreive the describe function result. They are as follows:
I20151214-09:20:20.381(-8)? Getting inside soap client creation method
I20151214-09:20:20.722(-8)? Exception while invoking method 'createSoapClient' TypeError: Cannot call method 'describe' of undefined
I20151214-09:20:20.723(-8)? at Object.Soap.createClient (packages/zardak_soap/packages/zardak_soap.js:37:1)
I20151214-09:20:20.724(-8)? at [object Object].Meteor.methods.createSoapClient (controllers/server/testFiles.js:21:1)
I20151214-09:20:20.724(-8)? at maybeAuditArgumentChecks (livedata_server.js:1698:12)
I20151214-09:20:20.725(-8)? at livedata_server.js:708:19
I20151214-09:20:20.725(-8)? at [object Object]._.extend.withValue (packages/meteor/packages/meteor.js:1013:1)
I20151214-09:20:20.726(-8)? at livedata_server.js:706:40
I20151214-09:20:20.726(-8)? at [object Object]._.extend.withValue (packages/meteor/packages/meteor.js:1013:1)
I20151214-09:20:20.726(-8)? at livedata_server.js:704:46
I20151214-09:20:20.727(-8)? at tryCallTwo (C:\Users\Media Center\AppData\Local\.meteor\packages\promise\0.5.1\npm\node_modules\meteor-promise\node_modules\promise\lib\core.js:45:5)
I20151214-09:20:20.727(-8)? at doResolve (C:\Users\Media Center\AppData\Local\.meteor\packages\promise\0.5.1\npm\node_modules\meteor-promise\node_modules\promise\lib\core.js:171:13)
I20151214-09:20:21.996(-8)? Getting inside the return of the create client
I20151214-09:20:22.007(-8)? { PRIMEStandardV1_1:
I20151214-09:20:22.008(-8)? { PRIMEStandardV1_1Soap:
I20151214-09:20:22.009(-8)? { RunTrip: [Object],
I20151214-09:20:22.009(-8)? ReverseGeocode: [Object],
I20151214-09:20:22.010(-8)? FindLocationsInRadius: [Object],
I20151214-09:20:22.010(-8)? FindLocationsOnRoute: [Object],
I20151214-09:20:22.010(-8)? FindLocationsInState: [Object],
I20151214-09:20:22.011(-8)? GetAverageDieselPriceInState: [Object],
I20151214-09:20:22.012(-8)? TestRadiusGeofence: [Object],
I20151214-09:20:22.012(-8)? TestRouteGeofence: [Object],
I20151214-09:20:22.013(-8)? RunSimpleTrip: [Object],
I20151214-09:20:22.013(-8)? Geocode: [Object],
I20151214-09:20:22.014(-8)? GetTodaysUSDieselAverage: [Object],
I20151214-09:20:22.014(-8)? GetTodaysCanadianDieselAverage: [Object],
I20151214-09:20:22.015(-8)? GetTripDistance: [Object],
I20151214-09:20:22.016(-8)? ValidateLocation: [Object] },
I20151214-09:20:22.017(-8)? PRIMEStandardV1_1Soap12:
I20151214-09:20:22.017(-8)? { RunTrip: [Object],
I20151214-09:20:22.018(-8)? ReverseGeocode: [Object],
I20151214-09:20:22.019(-8)? FindLocationsInRadius: [Object],
I20151214-09:20:22.021(-8)? FindLocationsOnRoute: [Object],
I20151214-09:20:22.021(-8)? FindLocationsInState: [Object],
I20151214-09:20:22.022(-8)? GetAverageDieselPriceInState: [Object],
I20151214-09:20:22.022(-8)? TestRadiusGeofence: [Object],
I20151214-09:20:22.023(-8)? TestRouteGeofence: [Object],
I20151214-09:20:22.023(-8)? RunSimpleTrip: [Object],
I20151214-09:20:22.024(-8)? Geocode: [Object],
I20151214-09:20:22.025(-8)? GetTodaysUSDieselAverage: [Object],
I20151214-09:20:22.025(-8)? GetTodaysCanadianDieselAverage: [Object],
I20151214-09:20:22.026(-8)? GetTripDistance: [Object],
I20151214-09:20:22.026(-8)? ValidateLocation: [Object] } } }
caseless:
I20151216-11:53:14.658(-8)? { dict:
I20151216-11:53:14.658(-8)? { 'cache-control': 'private',
I20151216-11:53:14.659(-8)? 'content-type': 'text/xml; charset=utf- 8',
I20151216-11:53:14.659(-8)? server: 'Microsoft-IIS/7.0',
I20151216-11:53:14.660(-8)? 'x-aspnet-version': '4.0.30319',
I20151216-11:53:14.660(-8)? 'x-powered-by': 'ASP.NET',
I20151216-11:53:14.661(-8)? date: 'Wed, 16 Dec 2015 19:40:29 GMT',
I20151216-11:53:14.661(-8)? connection: 'close',
I20151216-11:53:14.662(-8)? 'content-length': '441' } },
I20151216-11:53:14.662(-8)? pipe: [Function],
I20151216-11:53:14.663(-8)? addListener: [Function: addListener],
I20151216-11:53:14.664(-8)? on: [Function: addListener],
I20151216-11:53:14.665(-8)? pause: [Function],
I20151216-11:53:14.665(-8)? resume: [Function],
I20151216-11:53:14.666(-8)? read: [Function],
I20151216-11:53:14.666(-8)? body: 'soap:ServerServer was unable to process request. ---> Object reference not set to an instance of an object.' }
I20151216-11:53:16.716(-8)? Error: [object Object]
I20151216-11:53:16.722(-8)? { Envelope: { Body: { Fault: [Object] } } }
I20151216-11:53:16.723(-8)? undefined
As you can see I am able to connect. Now the part that is trowing me off is to actually call one of these functions. Below is the code I am using to try to call the "RunSimpleTrip". However when I console log the Result it is a huge jumble of messages that end up running the buffer out on my cmd window and I can only see back a little ways none of it making sense.
var url = 'http://prime.promiles.com/Webservices/v1_1/PRIMEStandardV1_1.asmx?wsdl';
var simpleTrip = {
AvoidTollRoads: false,
BorderOpen: true,
RoutingMethod: "PRACTICAL",
TripLegs: [{LocationText: "77611"},
{LocationText: "90210"}]
}
Soap.createClient(url, function(err, client) {
console.log(client.describe());
client.setSecurity(new Soap.BasicAuthSecurity('hoperd', 'mailaaron', 'bkkyt'));
client.PRIMEStandardV1_1.PRIMEStandardV1_1Soap.RunSimpleTrip(simpleTrip, function(err, result, raw, soapHeader) {
//console.log("Result: ");
console.log(result);
console.log("Error: " + err.root);
console.log(err.root);
console.log(soapHeader);
// result is a javascript object
// raw is the raw response
// soapHeader is the response soap header as a javascript object
})
});
From the API's documentation this is how they call the same function using .net
PRIMEEnterpriseV1 PRIME = new PRIMEEnterpriseV1();
//Authorization Credentials
Credentials c = new Credentials();
c.Username = "MyUsername;
c.Password = "MyPassword";
c.CompanyCode ="MyCompanyCode";
SimpleTrip st = new SimpleTrip();
st.AvoidTollRoads = false;
st.BorderOpen = true;
st.RoutingMethod = com.promiles.PRIME.Enterprise.RouteMethod.PRACTICAL;
TripLeg[] Legs = new TripLeg[2];
//Origin
TripLeg t = new TripLeg();
t.LocationText = "77611";
Legs[0] = t;
//Destination
t = new TripLeg();
t.LocationText = "90210";
Legs[1] = t;
st.TripLegs = Legs;
//Call Function
SimpleTrip rt = PRIME.RunSimpleTrip(c, st);
I am hoping someone our there has a clue to this mystery for me or can point me in the right direction as to how to properly connect this this. Any and all help will be greatly appreciated.
So after much trial and error I was able to figure this out. The below code works to call the SimpleTrip and return a proper response from the server. My TripLegs arg still isn't 100% correct to what the SOAP is looking for but the code and the way to call it is.
var url = 'http://prime.promiles.com/Webservices/v1_1/PRIMEStandardV1_1.asmx?wsdl';
var credentials = { Username: "xxxxx",
Password: "xxxxxx",
CompanyCode: "xxxxx"
};
var simpleTrip = {
AvoidTollRoads: false,
BorderOpen: true,
RoutingMethod: "PRACTICAL",
VehicleType: "Tractor2AxleTrailer2Axle",
TripLegs: [{Location: {LocationText: "77611"}},
{Location: {LocationText: "90210"}}]
}
args = {c: credentials, BasicTrip: simpleTrip};
Soap.createClient(url, function(err, client) {
console.log(err);
console.log(simpleTrip);
client.RunSimpleTrip(args, function(err, result, raw, soapHeader) {
console.log(result);
//console.log(err.root);
console.log(err.root.Envelope);
})
});

Resources