How to pass data from Server to Client in Meteor - javascript

I am Learning Meteor and Javascript. I am using an npm package to get meta data of an url on the server side. This works fine. But I get undefined when passing that result back to client. Would appreciate some help.
Here is my code
if (Meteor.isClient) {
Meteor.call('getMetaData', "http://www.bbc.co.uk/news", function (err, data) {
if (err) {
console.log("error", err);
};
console.log("Meta data: " + data); //shows undefined
});
}
if (Meteor.isServer) {
Meteor.startup(function () {
var preview = Meteor.npmRequire('page-previewer');
Meteor.methods({
getMetaData: function (url) {
preview(url, function (err, data) {
if (!err) {
console.log(data); //Works fine
return data;
}
});
}
})
});
}

You need to convert the preview function to an synchronous function,using Future like this, this will make this function wait normal err,data callbacks into a synchronous function.
var Future = Npm.require('fibers/future'),
preview = Meteor.npmRequire('page-previewer');
Meteor.methods({
getMetaData: function(url) {
var f = new Future();
preview(url, function(err, data) {
if (!err) {
return f.return(data);
}
});
return f.wait();
}
});
Now this snippet should work
if (Meteor.isClient) {
Meteor.call('getMetaData', "http://www.bbc.co.uk/news", function (err, data) {
if (err) {
console.log("error", err);
}else{
console.log("Meta data: " + data); //shows undefined
}
});
};

try using else block to get the meta data. here's a solution of a similar problem .
https://forums.meteor.com/t/client-getting-undefined-for-server-method/6129/4?u=faysal
so basically you need to add only one extra line
else{ console.log('metadata '+ data);}

Related

How to return a list of SQS queues in a module exports function?

I'm very new to node.js so I think I'm missing something obvious here.
I'm simply trying to get a list of SQS queues using aws-sdk and return them from a module to be accessible to other code. list_queues is the function in question.
The code below works to an extent, I see a "success" log and a log of a string array of all my queues, however, the function does not return that array to the caller and I don't understand why.
const AWS = require('aws-sdk');
AWS.config.update({region: 'eu-west-1'});
var sqs;
var sts = new AWS.STS();
sts.assumeRole({
RoleArn: 'arn:aws:iam::xxxxx:role/UserRole',
RoleSessionName: 'NodeDeveloperRoleSession'
}, function(err, data) {
if (err) { // an error occurred
console.log('Cannot assume role :(');
console.log(err, err.stack);
} else { // successful response
console.log('Assumed role success :)');
AWS.config.update({
accessKeyId: data.Credentials.AccessKeyId,
secretAccessKey: data.Credentials.SecretAccessKey,
sessionToken: data.Credentials.SessionToken
});
sqs = new AWS.SQS({apiVersion: '2012-11-05'});
}
});
exports.list_queues = function() {
sqs.listQueues({}, function(err, data) {
if (err) {
console.log("Error", err);
} else {
console.log("success");
console.log(data.QueueUrls);
return data.QueueUrls;
}
});
}
Any help is appreciated
exports.list_queues = function() { // 2. but you actually want to return from this one
sqs.listQueues({}, function(err, data) { <-----------------
if (err) { |
console.log("Error", err); |
} else { |
console.log("success"); |
console.log(data.QueueUrls); |
return data.QueueUrls; // 1. you are returning from this one
}
});
}
there are two ways you can make it work
Promise based
exports.list_queues = function() {
return sqs.listQueues({}).promise().then((data) => data.QueueUrls);
}
// and in another file you would:
const {list_queues} = require('./list_queues.js');
list_queues.then((queues) => console.log(queues));
Callback based
exports.list_queues = function(cb) { // notice I added callback here
sqs.listQueues({}, function(err, data) {
if (err) {
console.log("Error", err);
} else {
console.log("success");
console.log(data.QueueUrls);
cb(data.QueueUrls);
}
});
}
// and in another file you would:
const {list_queues} = require('./list_queues.js');
list_queues(function(queues) {
console.log(queues);
});
I strongly recommend you to use promise based approach, since it's much more readable and you can make use of async/await on it, which is great.

Wait for Meteor.call result on Client

I am new to JavaScript.I am not understanding how to wait for a result of an Meteor.call method.
This is my code
//client/main.js
//Added the callback
Template.hello.events({
'click button'(event, instance) {
// increment the counter when button is clicked
instance.counter.set(instance.counter.get() + 1);
var res = Meteor.call("callMeLater","sanj",function (err,res) {
if (err) {
console.log(err);
} else {
console.log("this is the result main ", res);
}
});
console.log("this is the result ", res);
}
//server/main.js
Meteor.methods({
callMeLater :function (name) {
var callMeLaterSync =Meteor.wrapAsync(callMeLaterAsync);
var result = callMeLaterSync(name);
console.log("this is the test", result);
return result;
}
});
var callMeLaterAsync = function (name,cb) {
setTimeout(function () {
cb && cb (null ,"hey there, "+name);
},2000);
};
On the console, i get
this is the result undefined
this is the result main hey there, sanj
How do i wait for the result of Meteor.call by blocking the execution at the client.
Please help
Thanks
Just put your code into a callback method.
Meteor.call('callMeLater',"sanj", function(err, res){
if (err) {
console.log(err);
} else {
console.log("this is the result ", res);
}
});

returning data from node mssql execute functions

I'm using mssql(Microsoft SQL Server client for Node.js) package from npm.I'm trying to execute a stored procedure residing in my sql server database.Everything works fine.However what I want to do is return the recordsets so that i can export this to be used in other module.Below is what I'm trying to do.
function monthlyIceCreamSalesReport (scope){
var connObj = connConfig();
connObj.conn.connect(function(err){
if(err){
console.log(err);
return;
}
connObj.req.input('Month',4);
connObj.req.input('Year',2016);
connObj.req.execute('<myStoredProcedure>', function(err, recordsets, returnValue){
if(err){
console.log(err);
}
else {
console.log(recordsets[0]); // successfully receiving the value
}
connObj.conn.close();
});
});
console.log('check for recordsets', recordsets[0]); // undefined
return recordsets[0];
}
var sqlServerObj = {
monICSalesReport : monthlyIceCreamSalesReport,
};
module.exports = sqlServerObj;
As shown in the code snippet, since the value of recordsets[0] is undefined, exporting this function is of no use.
You can't return this way in async nature. You can get it by passing the callback function
Try to give a callback function like this
function monthlyIceCreamSalesReport(scope, callback) { // pass a callback to get value
var connObj = connConfig();
connObj.conn.connect(function(err) {
if (err) {
console.log(err);
return;
}
connObj.req.input('Month', 4);
connObj.req.input('Year', 2016);
connObj.req.execute('<myStoredProcedure>', function(err, recordsets, returnValue) {
if (err) {
console.log(err);
} else {
console.log(recordsets[0]);
connObj.conn.close();
return callback(null, recordsets[0]); //return as a callback here and get that value in callback from where you called this function
}
});
});
}
var sqlServerObj = {
monICSalesReport: monthlyIceCreamSalesReport,
};
module.exports = sqlServerObj;
Note: See the comment to understand the changes
recordsets[0] is undefinded, because is defined only in connObj.req.execute function scope. You may do this in this way:
function monthlyIceCreamSalesReport (scope, cb){
var connObj = connConfig();
connObj.conn.connect(function(err){
if(err){
console.log(err);
return cb(Error("Something wrong"));
}
connObj.req.input('Month',4);
connObj.req.input('Year',2016);
connObj.req.execute('<myStoredProcedure>', function(err, recordsets, returnValue){
if(err){
console.log(err);
connObj.conn.close();
return cb(Error("Something wrong"));
}
else {
console.log(recordsets[0]); // successfully receiving the value
connObj.conn.close();
return cb(recordsets[0]);
}
});
});
}
var sqlServerObj = {
monICSalesReport : monthlyIceCreamSalesReport,
};
module.exports = sqlServerObj;

Javascript Node.js overwrite File completely

i have an application which needs a data.json file in order to draw a d3-graph. However i need to update that file on an onClick-Event:
d3.select("#updatebutton").on("click", function(e) {
try{
$.get('https://localhost:4444/data', function(data) {
});
}
catch (e) {
alert('Error: ' + e);
}
});
Above is the update-Button with the jquery-call. In my app.js File I am using it like this:
app.get('/data', function(req, res, next) {
try{
getJSON();
}
catch(e) {
alert('Error');
}
});
The getJSON()-Function is received Data over an https-Request, processes that data and saves it to data.json:
function getJSON() {
var req = https.get(options, function(response) {
// handle the response
var res_data = '';
response.on('data', function(chunk) {
res_data += chunk;
});
response.on('end', function() {
//process data
// save to file
fs.writeFile(filePath, JSON.stringify(finalJson), function(err) {
if (err)
throw err;
});
});
});
}
However if i click on my updateButton repeatedly after seconds, it seems that data.json is not overwritten but the file gets bigger and bigger, means that data is added to the file instead of overwritten.
What am I doing wrong?
Thanks for help.
Since you use app.get as your route, I guess you are using express.
In your routes definition:
var getData = (function() {
var callbacks = [];
function executeCallbacks(err, data) {
for (var i = 0; i < callbacks.length; i++) {
callbacks[i](err, data);
}
callbacks = [];
}
return function(cb) {
callbacks.push(cb);
if( callbacks.length === 1 ) {
var req = https.get(options, function(response) {
// handle the response
var res_data = '';
response.on('data', function(chunk) {
res_data += chunk;
});
response.once('end', function() {
// process data here
// save to file
fs.writeFile(filePath, JSON.stringify(finalJson), function(err) {
if (err) {
// call error handler
return executeCallbacks(err);
}
executeCallbacks(null, body);
});
});
response.once('error', function() {
return executeCallbacks(err);
});
}
req.end();
}
};
})();
app.get('/data', function(req, res, next) {
getData(function(err, data) {
if(err) {
return next(err);
}
return data;
});
});
In your browser js file:
d3.select("#updatebutton").on("click", function(e) {
$.get( 'https://localhost:4444/data', function(data) {
alert( "success" );
var json = JSON.parse(data);
})
.fail(function() {
alert( "error" );
});
});
I see you use try / catch around callback functions. The callback function fires after the original function completes. So don't use Try / Catch around callback function.
Read: https://strongloop.com/strongblog/async-error-handling-expressjs-es7-promises-generators/

Meteor.js: Wait for server to finish

I'm running into a scenario where my meteor server call is posting to a remote URL and then returning the result. However, my meteor client is expecting a result right away and its receiving an empty string (the default return).
What is the correct way of implementing this?
Meteor.methods({
run: function(options){
return HTTP.post(apiUrl, {
params:
{
"headers": headers
}
},
function (error, result)
{
if (error)
{
console.log("error: " + error);
}
else
{
console.log("result: " + JSON.stringify(result));
console.log(result.content);
}
})
});
on my client
Meteor.call('run', '1', function(err,response) {
if(err) {
console.log(err);
return;
}else{
r = response;
console.log(JSON.stringify(r));
FileSystem.update({ _id: fileid }, { $set: {taskid:taskid} }, function (e, t) {
if (e) {
}else{
}
});
}
});
I'm expecting on the client side that it waits for the full result to come in which contains the desired data to save to data base (taskid).
You are calling HTTP.post asynchronously. Just remove the callback function and it becomes synchronous, i.e., you will get a return value that contains the result of the call:
Meteor.methods({
run: function(options){
return HTTP.post(apiUrl, {
params:
{
"headers": headers
}
});
});
});

Categories

Resources