0

I am using Nodejs Express. I currently have a script that produces an array of objects from Google API. I need to take that JSON data and use it in my templates. How can I call the function in my script from my route file?

This is my script file: var Spreadsheet = require('edit-google-spreadsheet');

Spreadsheet.load({
  debug: true,
  spreadsheetId: '1eWmSV4Eq-se4gZSvBfW-J-lEOLwNopEfMavZByJ-qD8',
  worksheetId: 'owrromd',

  //    1. Username and Password
  username: 'user',
  password: 'pass',

}, function sheetReady(err, spreadsheet) {
  //use speadsheet!

  spreadsheet.receive(function(err, rows, info) {
    if (err) throw err;

    var announcementArray = [];

    //console.log(rows);
    for (x in rows) {
      var eachObject = rows[x]

      var side = eachObject['1'];
      //console.log(side);

      var type = eachObject['2'];
      //console.log(type);

      var announcement = eachObject['3'];
      //console.log(announcement);

      var announcementItem = {};
      announcementItem.side = side;
      announcementItem.type = type;
      announcementItem.announcement = announcement;

      announcementArray.push(announcementItem);
    }

    announcementArray.shift();
    console.log(announcementArray);
  });
});

This is my route js file:

module.exports=function(app){

    app.get('/', function(req,res){
        res.render('index', {title:"Home page", description:"The is the description"});
    });
}
6
  • Just so I am clear - is announcementArray the content that you are looking to incorporate in your template? Commented Mar 20, 2015 at 3:33
  • You can make your script file a npm module and use it in the route.js file. Commented Mar 20, 2015 at 3:34
  • Yes announcementArray has the data I want to access Commented Mar 20, 2015 at 3:34
  • I am new to node...how do I make a npm module and use it in the route? Commented Mar 20, 2015 at 3:37
  • @conanak99 - Why would one turn user code into an NPM module? Nevermind - I see what you meant now. Commented Mar 20, 2015 at 3:42

2 Answers 2

1

Change the content of the script file, let's call it loadSheet.js

var Spreadsheet = require('edit-google-spreadsheet');

function loadSheet() {
  Spreadsheet.load({
    debug: true,
    spreadsheetId: '1eWmSV4Eq-se4gZSvBfW-J-lEOLwNopEfMavZByJ-qD8',
    worksheetId: 'owrromd',

    //    1. Username and Password
    username: 'user',
    password: 'pass',

  }, function sheetReady(err, spreadsheet) {
    //use speadsheet!

    spreadsheet.receive(function(err, rows, info) {
      if (err) throw err;

      var announcementArray = [];

      //console.log(rows);
      for (x in rows) {
        var eachObject = rows[x]

        var side = eachObject['1'];
        //console.log(side);

        var type = eachObject['2'];
        //console.log(type);

        var announcement = eachObject['3'];
        //console.log(announcement);

        var announcementItem = {};
        announcementItem.side = side;
        announcementItem.type = type;
        announcementItem.announcement = announcement;

        announcementArray.push(announcementItem);
      }

      announcementArray.shift();
      console.log(announcementArray);
    });
  });
}

//Export it to module
exports.loadSheet = loadSheet;

Then in the route js:

var ls = require('./loadSheet.js'); //Load the module, get the name of the script file

app.get('/', function(req,res){
        res.render('index', {title:"Home page", description:"The is the description"});
        ls.loadSheet();
});
Sign up to request clarification or add additional context in comments.

6 Comments

Got it - module form. You weren't suggesting it needed to go through npm. This is correct and saved me the typing. Thanks
Couple of questions: 1. what is exports.loadsheet = loadsheet; doing? Is this the same thing as module.exports? Where in the route is this module being called? 2. Now that I have loaded the module in my routes, how do I access the json data?
1) Yes exports and module.exports are functionally equivalent here. I personally am a module.exports guy. 2) I did not look at the answer thoroughly when I said it was correct. You will need to adapt the exported function a bit. Give me a moment.
1. So I could have done module.exports = loadSheet; Does it matter what name I give this module? I'm not calling it in my route anywhere I see.
You could have but that's really not how it is done. It's like you can wear your socks over your shoes, but nobody does it that way. Oh, and no it doesn't matter regarding the name. You could call it MaryPoppins if you'd like. Did you look at the answer I provided? I just now realized I did not copy the needed require line in to the routes section of my answer. will correct.
|
0

So you'd adapt the module the other response created. But you are going to need to give a callback to loadSheet. I am cutting out the main body of that function for clarity.

var Spreadsheet = require('edit-google-spreadsheet');

function loadSheet(theCallback) {   //take a callback here.
  Spreadsheet.load({...yourdata...}, function sheetReady(...) {

      // create your announcementArray
      // then call the callback
      theCallBack(undefined,announcementArray);
    });
  });
}

//Export it to module
exports.loadSheet = loadSheet;

Then, from your routes, you can get it like so:

var ls = require('./loadsheet.js'); // assumes in same dir as routes
app.get('/', function(req,res){
        ls.loadSheet(function(err,result){
            res.render('myTemplate',result);
        });
});

I am going to assume you can take care of getting the result data into your template. You can look in the index template to see how it pulls in the data. I don't know whether you are using Jade or EJS.

Note, this is all sort of hackish but addresses your functional question. Let me know if you need a little further direction.

2 Comments

Thanks so much for your help so far! Couple of things that I am confused/aren't working. 1. Where is theCallback(undefined,announcementArray); being used in my route file? 2. You passed two parameters in the loadSheet (err,result). Can't I just use the result parameter to spit out my json data and skip the callback that you defined in my script file? The code you gave me gave me an error that I had an unexpected token in the brackets in this code getAnnouncements.loadSheet(err,result){ res.render('announcements',result); }
@user3726872 Could you please post a github gist with the code you are running? [i.e. the code that is getting the error]. In answer to a couple of your questions, the callback is being defined inline in the call to it - ls.loadsheet(function... - . Also, looking at your comment here again - getAnnouncements.loadSheet(err,result){ res.render('announcements',result); was not what is in the code I wrote - you seem to be missing the function keyword and otherwise ill-formatted. Didn't your code editor clue you into the bad syntax? Look at my code again.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.