my first steps with node...
I want to access to the response status when calling a function like this:
var unirest = require('unirest');
function doPut(){
var Request = unirest.put('some_url').type('json').send('some_json');
return Request.end(function (response) {
return response.status;
});
}
console.log("Status is: " + doPut())
Inside the inner code, the value of status is "204" but when asking outside the function doput() i get an object,how can I pass the value from the inner function?
Thanks.
The reason [object Object] is returned is because you're just printing the object. Either (if you know the output format) print a specific value or use JSON.stringify(doput()).
Related
I'm trying to retrieve all the child then when there's match display.
I print the value in the console and my code work well there after few second, but when I print it in the agent as a message it show not available before the response because it does not wait.
Here is my code:
function retrieveContact(agent) {
var query = admin.database().ref("/contacts").orderByKey();
query.once("value")
.then(function(snapshot) {
snapshot.forEach(function(childSnapshot) {
var key = childSnapshot.key;
var childName = childSnapshot.child('name').val();
if (agent.parameters.name == childName) {
console.log('find ' + childName);
agent.add('The email address for ' + childName + ' is ' + childSnapshot.child('email').val());
}
// console.log('testMode'+childName);
}); //// .then
}); //// .once }
SO, how can I wait my response then let the agent show the result?
How can I include the promise concept in my code ?
You don't show your entire Handler function, but if you're doing async operations (such as reading from the firebase db) you must return the Promise. This is how the Handler Dispatcher knows to wait for the Promise to complete before returning a response to the user.
In your case, it is probably as simple as
return query.once("value")
// etc
I have a simple HTTP GET function that only needs to return the response in a function, but right now this function is returning void.
The code in sitechecks.js
var checkSite = () => {
https.get('https://itmagazin.info', (res, err) => {
if (res.statusCode === 200 && res.statusMessage === 'OK') {
return `The site returned: ${res.statusMessage}`
} else return `Error, the site returned: ${err.message}`
})
}
module.exports = checkSite
And when I import the module in index.js, the console returns [Function: checkSite] and not the value itself.
// Index.js
var extSiteCheck = require('./sitechecks')
// This console prints [Function: checkSite] instead of "OK"
console.log(extSiteCheck.checkSite)
However, if I add the return statement on http.get() in the function, the console prints undefined. So I thought that this undefined is a progress, but I don't understand why does it return undefined?
(return http.get() in the checkSite function)
Any help, tips is appreciated.
Because callbacks in JavaScript are asynchronous, you can't return from within a callback.
That means this
console.log(extSiteCheck.checkSite)
runs before the request comes back.
You can try console logging within your callback (instead of trying to return a value), in order to see this in practice. But basically, whatever you are trying to achieve with the results of your get request, you need to do inside the callback.
mebbe something like ... console.log( extSiteCheck.checkSite() );
Attempting to pass a responseHandler from a require rather than having it in the same file but getting error listener argument must be a function. console.log the require return, returns a function, so I don't see the issue?
var responseHandler = require("./downloader.js");
log(responseHandler); // Logs [Functions: responseHandler)
request = https.get(fileUrl, responseHandler); // Error "listener" argument must be a function (according to the log line above, it is!?)
If I swap out line 1 for the contents of downloader.js all works fine...
Content of downloader.js is just
var responseHandler = function(response){
// some code to process response.statusCode
response.on('data',function(chunk){//stuff});
response.on('error',function(e){//stuff});
response.on('end',function(e){//stuff});
}
exports.responseHandler = responseHandler;
I would like to keep the main file clean and small and have this working as a require, ideas?
If you want to only export the function you can do it with:
module.exports = responseHandler;
Then the imported value will be the function rather than an object with a function value:
var responseHandler = require("./downloader.js");
You will need to try doing:
request = https.get(fileUrl, responseHandler.responseHandler);
You're exporting an object that has a function called responseHandler, so you need to call it directly
Either you can export only function without name
module.exports = (response)=> {
// some code to process response.statusCode
response.on('data',function(chunk){//stuff});
response.on('error',function(e){//stuff});
response.on('end',function(e){//stuff});
}
Ok so i am using a method to make a request and pull some tables from another URL
Meteor.methods({
gimmetitle: function () {
var url = 'http://wiki.warthunder.com/index.php?title=B-17G_Flying_Fortress';
request(url, function(err, response, body) {
$ = cheerio.load(body);
var text = $('.flight-parameters td').text();
console.log(text);
return text;
});
}
});
When called the td's in the table succesfully print to the server console: http://prntscr.com/721pjh
Buuut, when that text is returned from that method to this client code, undefined is printed to the console:
Template.title.events({
'click #thebutton': function () {
Meteor.call('gimmetitle', function(error, result){
Session.set('gogle', result);
});
var avar = Session.get('gogle');
console.log(avar);
}
});
Ideas?
You need to understand two different things here :
On the client side, making some calls to the server is always asynchronous, because we have to deal with network latency. That's why we use callbacks to fetch the result of Meteor methods : this code is executed some time in the future, not right away.
This is why Session.set('gogle', result); is actually executed AFTER var avar = Session.get('gogle'); even though it appears before in your event handler code flow.
Contrary to template helpers, event handlers are NOT reactive, so it means that when you set the Session variable to the result of the method, the event handler code is not automatically reexecuted with the new value of Session.get('gogle').
You'll need to either do something with the result right in the Meteor method callback, or use a reactive computation (template helpers or Tracker.autorun) depending on Session.get('gogle') to rerun whenever the reactive data source is modified, and use the new value fetched from the server and assigned to the Session variable.
Quick update..Was able to fix this with just 1 line of code lol.
instead of request(url, function(err, response, body) i used the froatsnook:request package and used var result = request.getSync(url, {encoding: null}); and then just replaced $ = cheerio.load(body); with $ = cheerio.load(result.body);.
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}));