0

I'm trying to fetch events from Google Calendar. I have code to do that in a js file (googlecal.js) I have posted the function that lists the events. Now I want to write a new js file and get the list of these events from the googlecal.js file. Fairly new to JS, would appreciate a direction for this.

function listEvents(auth) {
  const calendar = google.calendar({version: 'v3', auth});
  calendar.events.list({
    calendarId: 'primary',
    timeMin: (new Date()).toISOString(),
    maxResults: 10,
    singleEvents: true,
    orderBy: 'startTime',
  }, (err, res) => {
    if (err) return console.log('The API returned an error: ' + err);
    const eve = res.data.items;
    if (eve.length) {
      //console.log('Upcoming 10 events:');
      eve.map((event, i) => {
        const start = event.start.dateTime || event.start.date;
        //console.log(`${start} - ${event.summary}`);

        var attendee = event.attendees;

      });
    } else {
      console.log('No upcoming events found.');
    }
  });
}

I tried to use module.exports or exporting this function and importing in a new file. But I am not very sure how to export it and import in the other js file, which is where I am facing the problem.

2 Answers2

0

You can export this function as the top level/default through module.exports = listEvents if this is all you're interested in exporting, and use it as const listEvents = require('./googlecal') (the path would mean that the importer is at the same level).

Another popular convention is to export as an object so you have space to expand your module's exported funtionalities:

module.exports = { 
  listEvents,
  // future stuff
}

And use it so by leveraging destructuring: const { listEvents } = require('./googlecal')

woozyking
  • 4,880
  • 1
  • 23
  • 29
  • I did that. But I can't fetch the variable 'attendee' from the other js file. It gives me undefines – Deepen Panchal May 03 '19 at 17:40
  • @DeepenPanchal that’s a different problem. The function itself should `return` something, probably the fetched object from google calendars. That is not just a js thing. – woozyking May 03 '19 at 17:43
0

If your environment support ES6 Module syntax, you can use import and export, if not then you should use require and module.exports.

if you are going to use module.exports then just add module.exports = { listEvents } and importing it with const { listEvents } = require('./path/to/your/file')

You can read this for using export:

How to use import/export