Nodejs get request, body into variable - node.js

Im trying to take content of body into a variable but it says 0.
Where is wrong here? :|
var utc = 0;
request.get('http://localhost/actions.php?utc',function(err,response,body) {
utc = body;
});
console.log(utc);

Your log statement is executed earlier than the callback of the request call. Try to put log statement into the callback, right after the assignment.

Related

How to handle response from JSON but started with numbers

how to handle JSON response, I got this response but I don't know how to handle it. I know variable can't started with numbers, so?
let result = [{"1d":{"volume":"22275409068573.73","price_change":"56446.71564507","price_change_pct":"0.0121","volume_change":"-13864857829188.44","volume_change_pct":"-0.3836","market_cap_change":"9216448958327.75","market_cap_change_pct":"0.0121"}}];
How to parsing"1d"?
I try JSON.parse(result[0].1d); but error happened
If you don't want to use ["prop"] to get value, you can change all props that starts with a number like in the example.
Check this link
var json = JSON.stringify(result);
json = json.replace(/,"[0-9]|{"[0-9]/g, function (x) {
return x.substring(0,1)+'"num'+x.substring(2);
});
result = JSON.parse(json);
var whatIwant = result.num1d;
You can't use JSON.parse for JSON object.
If you want to get value of 1d. Try this
result[0]["1d"]

How to bring out the request-promise result to the outside scope?

How to bring out the request-promise result to the outside scope?
I don't know why my bot echo 10 instead of 100.
enter image description here
This is the result I tried to get with await
enter image description here
In your code, change rp().then... to await rp().then... Js is asynchronous. While the rp() function runs, it takes some time. So, the code below it gets executed in that time.Hence, value of abc is never changed from inside the rp() function.
I'd recommend reading a bit more about promises and async/await in JavaScript, but to answer your question:
Your getAreaWeather() function is an async function, so you don't need to use an ES6 promise chain (.then() and .catch()), and you need to actually make sure your rp() promise resolves before you return anything. Your current function is setting abc to 10, then starting the request in rp(), but it immediately returns abc (which still equals 10 because the request hasn't finished yet)
This is just an example of how to fix the promises; I don't know if there are any issues with the HTML parsing.
async function getAreaWeather() {
var abc = 10;
var weathers = [];
var options = {/*what you have in your screenshot*/};
try {
// Wait for the rp() promise to resolve
var $ = await rp(options);
// Use $ however you want...
abc = 100;
return abc;
} catch (err) {
console.error(err);
}
// You could also return abc here if you want, but be aware it'll still equal 10 if the rp() throws an error
}

Nodejs Callback: How to define a Callback?

I am reviewing a sample nodejs server code, which is working fine. but could not understand the following code:
var handlers = {};
// Creating a sample handler
handlers.sample = function(data,callback){
callback(406,{'name':'sample handler'}); // How is this line of code working??
};
// Creating a not found handler
handlers.notFound = function(data,callback){
callback(404); // How is this line of code working??
};
In the entire code there is no implementation of "callback" function then how
callback(406,{'name':'sample handler'});
and
callback(404);
are working?
Please suggest. Thanks.
callback isn't implemented in the code you posted; it's a named parameter.
To call one of the functions that requires a callback, you'll need to pass it in as an argument, like:
handlers.sample("some data", () => console.log("I'm in a callback!));
The first argument ("some data") goes in the data parameter, and the second argument (() => console.log("I'm in a callback!)) goes in the callback parameter. When callback(404) is run, it executes the callback function (in the above example, it would do console.log("I'm in a callback!)).
Basically, when you call handlers.sample, you should pass a function as your second argument, and that function will be called, usually asynchronously, and presumably after something is done with the data you pass as the first argument. For example, based on the code you provided:
handlers.sample(dataObject, (number, object) => {
console.log(number)
console.log(object.name)
})
would yield this result in the console:
406
sample handler
I’m curious if this is a public library you are seeing this code in, so we can take a closer look?
I did a further digging in into this and found that
selectedHandler
in the following code (this is not mentioned in the question) is getting resolved into handlers.sample or handlers.notFound variable names based on some logic (which is not mentioned here)
selectedHandler(data,function(status,payloadData){
// somelogic with the status and payloadData
});
And second parameter of this function which is a complete function in itself
function(status,payloadData){
// somelogic with the status and payloadData
}
is going as the second parameter in handlers.sample or handlers.notFound which is a Callback. So execution of Callback in the current context is execution of this function (this function is anonymous because it has no name and getting executed as Callback)

Variable outside callback is empty [duplicate]

This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 6 years ago.
I'm a NodeJS beginner and actually I try to work with a NoSQL Database for building a simple login via. Digest Authentication. I also created an module called "users" wich is loaded in my application.
Now when I try to call the data results inside the callback function I get my correct data. In the same callback I assign the returned data to the variable records. When I call the variable outside I will get the result null - where is the error?
var dbdriver = require('nosql'),
dbfile = dbdriver.load("./db.nosql"),
records = null
dbfile.top(1000).callback(function(err, response) {
(function(users) {
records = users
console.log(users) // Here i get the wanted result
})(response)
})
console.log(records) // Here the result is empty
thank you very much :)
Since the you are calling console.log(users) inside the callback, the value is reflected correctly. And this is a behavior of asynchronous calls in javascript. So the last line console.log(records) would probably be run first before the callback executes and so records up to this point does not have any value.
So I would suggest that you make the a function that does something on users and call it inside the callback.
var dbdriver = require('nosql'),
dbfile = dbdriver.load("./db.nosql"),
records = null
dbfile.top(1000).callback(function(err, response) {
(function(users) {
//records = users
//console.log(users) // Here i get the wanted result
doSomethingToUsers(users);
})(response)
})
function doSomethingToUsers(users) {
// do something to users
}
//console.log(records) // Here the result is empty
Looks like a timing issue to me. When console.log(records) in the outer scope gets called before the (async) callback function was called, records contains exactly the value that was initially assigned (records = null).
Only after calling the async callback, the records variable will be set.
Does this help?

Sending HTTP response in node.js

I am trying to send an http response in node to print results in the browser. The simplified source code is down below. Basically, all the variables are defined somewhere in the program, so that shouldn't be problem. When I try to run the script, I keep getting the error:
http.js:783
throw new TypeError('first argument must be a string or Buffer');
TypeError: first argument must be a string or Buffer
So can someone familiar with node.js or javascript syntax let me know what the problem is?
upload = function(req, res) {
var fileInfos = [obj, obj]; //defined as an array of objects
var counter = 0;
counter -= 1;
if (!counter) {
res.end({files: fileInfos}); //files is defined.
}
};
async.forEach(urls, downloadFile, function (err) { //all params defined.
if(err){
console.error("err");
throw err;
}
else{
http.createServer(function(req, res){
upload(req1, res); //req1 defined as an array of objects.
}).listen(3000, "127.0.0.1");
console.log('Server running at http://127.0.0.1:3000/');
}
});
This error is often caused by an attempt to call response.write with the wrong type of parameter. Looking at the documentation it suggests:
response.end([data], [encoding])#
This method signals to the server that all of the response headers and body have been sent; that server should consider this message complete. The method, response.end(), MUST be called on each response.
If data is specified, it is equivalent to calling response.write(data, encoding) followed by response.end().
Now response.write( chunk, encoding ) expects the chunk to be a string, so it seems possible that when you are calling res.end({files: fileInfos}) it is unable to write the content of that object as a string.
You can use JSON.stringify() to convert the JavaScript object to string before sending it to the client.
res.end(JSON.stringify({files: fileInfos}));

Resources