How to use a package after npm install

I want to use the node package “gtfs-realtime-bindings” in my ionic project.
You can find it here: https://www.npmjs.com/package/gtfs-realtime-bindings

But once I do npm install gtfs-realtime-bindings then I add the example code into one of my controllers:

angular.module('app.controllers', [])
  .controller('MapCtrl', function($scope, $state) {
    var GtfsRealtimeBindings = require('gtfs-realtime-bindings');
    var request = require('request');

    var requestSettings = {
      method: 'GET',
      url: 'URL OF YOUR GTFS-REALTIME SOURCE GOES HERE',
      encoding: null
    };
    request(requestSettings, function (error, response, body) {
      if (!error && response.statusCode == 200) {
        var feed = GtfsRealtimeBindings.FeedMessage.decode(body);
        feed.entity.forEach(function(entity) {
          if (entity.trip_update) {
            console.log(entity.trip_update);
          }
        });
      }
    });
  });

I get the error… Error: Can't find variable: require.

What other js code needs to be added?

So you can use a different import statement

Instead of var GtfsRealtimeBindings = require('gtfs-realtime-bindings');
use import * as GtfsRealtimeBindings from 'gtfs-realtime-bindings';

Same thing for request

Where would I put import? I updated the question to accordingly.

Ahh this is an angular 1 project, my mistake.
Hmm, I don’t believe this is something you can use then. It’s for node,

These bindings are designed to be used in the Node.js environment

If I update to Ionic 2 can I do this?

No, it’s just meant for node environment, so a node server or something similar

1 Like