nodejs calling a variable outside of a scope - javascript

I am working with nodejs and in the JS file i have the code below to retrieve data .
when i try to use the data outside the scope it doesn't work i get the content undefined the whloe time ..
var data = {};
request.get({url: 'https://my-host/Mypath'}, function(err, response, body) {
if (err) {
console.error(err);
data.err = err;
}
data= body;
});
console.log('Data: ', data);
My main problem is that i have to send res.render with the data and i need to do multiple requests to the server .

You are making an async call. console.log() is executed before the request. Try moving that console.log into the request callback and it will work.
To use it out of the request function, you need to return a promise. Maybe try the Q tool:
https://github.com/kriskowal/q

Related

Getting the HTML of a website into a variable using the Request Library

I'm using Node.JS with the Library "Request" and for some reason, I can't save the HTML from the request into a variable.
var GarfHTML;
Request(GarfURL, (error, response, body) => {
GarfHTML = body;
});
console.log(GarfHTML);
I want to have it saved inside of the variable for use outside of the method, but the result returns as "undefined". When I do console.log inside of the Request method, the HTML is actually printed.
This code is executed before GarfHTMLis filled. Therefore when you try to access it, it might be still empty.These are Async functions. if you want to access it outside try
Request(GarfURL, (error, response, body) => {
let GarfHTML = body;
triggered(GarfHTML);
});
function triggered(GarfHTML) {
console.log(GarfHTML);
// Do your work on GarfHTML
}

NodeJS getting response from net socket write

I'm trying to get a response from specific requests via the write function.
I'm connected to an equipment via the net module (which is the only way to communicate with it). Currently, I have an .on('data',function) to listen to responses from the said equipment. I can send commands via the write functions to which I am expecting to receive a line of response. How can I go about doing this?
Current code:
server = net.Socket();
// connect to server
server.connect(<port>,<ip>,()=>{
console.log("Connected to server!");
});
// log data coming from the server
server.on("data",(data)=>{
console.log(''+data);
});
// send command to server
exports.write = function(command){
server.write(command+"\r\n");
};
This is a working code. Sending a command to the equipment via server.write returns a response which right now only appears in Terminal. I'd like to return that response right after the write request. Preferably within the exports.write function.
Add a callback argument to your exports.write function can solve your problem.
exports.write = function(command, callback){
server.write(command+"\r\n");
server.on('data', function (data) {
//this data is a Buffer object
callback(null, data)
});
server.on('error', function (error) {
callback(error, null)
});
};
call your write function
var server = require('./serverFilePath')
server.write('callback works', function(error, data){
console.log('Received: ' + data)
})

Need clarification on calling Meteor methods asynchronously

So i've been doing some reading and I think I have a general grasp on this subject but could use some insight from someone more experienced. I've been trying to write a simple RSS reader in Meteor and have been facing some issues with calling the Meteor method asynchronously. I currently define the method on the server(synchronously) and call it on the client(asynchronously). What I don't understand is that when I try to make the HTTP.call on the server, I return an undefined value passed to my client if I pass a callback into the request. But when I make the API request synchronously everything seems to work fine. Is this the normal behavior I should expect/the way I should be making the API call?
Meteor.methods({
getSubReddit(subreddit) {
this.unblock();
const url = 'http://www.reddit.com/r/' + subreddit + '/.rss';
const response = HTTP.get(url, {}, (err, res) => {
if(!err) {
//console.log(res.content);
return res;
} else {
return err;
}
});
}
});
Here's the method defined on the server side. Note that logging res.content shows that I'm actually getting the right content back from the call. I've tried reading some other answers on the topic and seen some things about using Future/wrapAsync, but I'm not sure I get it. Any help would be greatly appreciated!
The HTTP.get is doing async work, so callback passed to it will be called out of this meteor method call context.
To get desired result you should do it like this:
Meteor.methods({
getSubReddit(subreddit) {
// IMPORTANT: unblock methods call queue
this.unblock();
const url = 'http://www.reddit.com/r/' + subreddit + '/.rss';
const httpGetSync = Meteor.wrapAsync(HTTP.get);
try {
const response = httpGetSync(url, {});
//console.log(response.content);
return response.content;
} catch (err) {
// pass error to client
throw new Meteor.Error(...);
}
}
});

JS, Async (lib), Express. response( ) inside async not working

I tried to call res() after some async stuff finishes, inside Async.waterfall([], cb)
But as it seems, the req/res objects are not available in that scope. I call them from my callback cb.
function (req, res, next) {
var query = req.query;
async.waterfall([
async.apply(userManager.register, query.username, query.email, query.password)
], function (err, result) {
if (err)
console.log(err);
if (err && err.internal == false)
return res(err); //TypeError: res is not a function
console.log(result);
});
The only solution I have in mind is, passing the req/res to my backend, and call it there.
But that would mean that my background code needs to have a req and res object. Moreover it returns something to my server, which is also bad.
Thanks for your help.
Your issue is not about scope. It's that res is not a function so you can't call it like res(err). res is an object with methods. You can send an error response either like this which will go to the default error handler in Express:
next(err)
Or like this:
res.status(500).send("Internal Error occurred").
which sends a 500 status on the response and then sends whatever content you want to describe the error.
I can't think of any circumstance where you want to pass the res object into your backend. Your backend should fetch and return data and then your route handler should turn that data or error into a response.

How to call a function at start in Node-Express, with dbconnection

I'm a little bit newbie with Nodejs. I'm working in a Nodejs - express solution (as webservice of an angularjs web). I want to send and e-mail when MSSSQL database query gives back some information. This is working well for me. The problem is this function should be call in the app.js (when the nodejs server starts), because the function don't should respond to any frontend/web call.
The function:
exports.sendMailBuy = function(req, res) {
//do stuff
}
The app.js
var silkcartCtrl = require('./controllers/silkcart.controller');
I need to connect with the database, so I've tried to call the funciont in the same function db connection (I'm using Tedious):
dbsqlservertoken.connect().then(function(err, req, res) {
console.log('Connection pool open for sql server');
silkcartCtrl.sendMailBuy(req, res);
}).catch(function(err) {
console.error('Error creating connection pool', err);
});
With this call I reach the function in the controller, but the req and res vars are empty, so the connection could not be done.
Any help will be appreciate.
Thanks in advance.
The .then() method is used when a Promise is returned. I'm not familiar with the libraries you're using, but your code indicates that connect() returns a Promise.
See Promises for more information.
In particular, the function passed to .then() takes a single argument which is the result resolved by the Promise. In your code, err is being assigned the result while req and res are undefined because the function only receives one argument.
req, res are not returned from connect callback function they are only acccessed using api requests e.g. app.post('/any route' , function(req, res))
You can use node_mailer module if you need req object to send email because with node_mailer you can send email without req object

Categories

Resources