包详细信息

gtfs

blinktaginc2.6kMIT4.17.4

Import GTFS transit data into SQLite and query routes, stops, times, fares and more

transit, gtfs, transportation, geojson

自述文件

➡️ Installation | Quick Start | TypeScript Support | Configuration | Query Methods ⬅️

node-GTFS



Import and Export GTFS transit data into SQLite. Query or change routes, stops, times, fares and more.

NPM


node-GTFS loads transit data in GTFS format into a SQLite database and provides some methods to query for agencies, routes, stops, times, fares, calendars and other GTFS data. It also offers spatial queries to find nearby stops, routes and agencies and can convert stops and shapes to geoJSON format. Additionally, this library can export data from the SQLite database back into GTFS (csv) format.

The library also supports importing GTFS-Realtime data into the same database. In order to keep the realtime database fresh, it uses SQLITE REPLACE which makes it very effective.

You can use it as a command-line tool or as a node.js module.

This library has four parts: the GTFS import script, GTFS export script and GTFS-Realtime update script and the query methods

Installation

To use this library as a command-line utility, install it globally with npm:

npm install gtfs -g

This will add the gtfs-import and gtfs-export scripts to your path.

If you are using this as a node module as part of an application, include it in your project's package.json file.

npm install gtfs

Quick Start

Command-line examples

gtfs-import --gtfsUrl http://www.bart.gov/dev/schedules/google_transit.zip

or

gtfs-import --gtfsPath /path/to/your/gtfs.zip

or

gtfs-import --gtfsPath /path/to/your/unzipped/gtfs

or

gtfs-import --configPath /path/to/your/custom-config.json

gtfs-export --configPath /path/to/your/custom-config.json

Code example

import { importGtfs } from 'gtfs';
import { readFile } from 'fs/promises';
import path from 'node:path';

const config = JSON.parse(
  await readFile(path.join(import.meta.dirname, 'config.json'))
);

try {
  await importGtfs(config);
} catch (error) {
  console.error(error);
}

Example Applications

GTFS-to-HTML GTFS-to-HTML uses node-gtfs for downloading, importing and querying GTFS data. It provides a good example of how to use this library and is used by over a dozen transit agencies to generate the timetables on their websites.
GTFS-to-geojson GTFS-to-geojson creates geoJSON files for transit routes for use in mapping. It uses node-gtfs for downloading, importing and querying GTFS data. It provides a good example of how to use this library.
GTFS-to-Chart GTFS-to-chart generates a stringline chart in D3 for all trips for a specific route using data from an agency's GTFS. It uses node-gtfs for downloading, importing and querying GTFS data.
GTFS Accessibility Validator GTFS Accessibility Validator checks for accessiblity-realted fields and files and flags any issues. It uses node-gtfs for downloading, importing and querying GTFS data.
GTFS-TTS GTFS-Text-to-Speech app tests GTFS stop name pronunciation for text-to-speech. It uses node-gtfs for loading stop names from GTFS data.
Transit Departures Widget Transit Departures Widget creates a realtime transit departures widget from GTFS and GTFS-Realtime data.

Command-Line Usage

The gtfs-import command-line utility will import GTFS into SQLite3.

The gtfs-export command-line utility will create GTFS from data previously imported into SQLite3.

gtfs-import Command-Line options

configPath

Allows specifying a path to a configuration json file. By default, node-gtfs will look for a config.json file in the directory it is being run from. Using a config.json file allows you specify more options than CLI arguments alone - see below.

gtfs-import --configPath /path/to/your/custom-config.json

gtfsPath

Specify a local path to GTFS, either zipped or unzipped.

gtfs-import --gtfsPath /path/to/your/gtfs.zip

or

gtfs-import --gtfsPath /path/to/your/unzipped/gtfs

gtfsUrl

Specify a URL to a zipped GTFS file.

gtfs-import --gtfsUrl http://www.bart.gov/dev/schedules/google_transit.zip

TypeScript Support

Basic TypeScript typings are included with this library. Please open an issue if you find any inconsistencies between the declared types and underlying code.

Configuration

Copy config-sample.json to config.json and then add your projects configuration to config.json.

cp config-sample.json config.json
option type description
agencies array An array of GTFS files to be imported, and which files to exclude.
csvOptions object Options passed to csv-parse for parsing GTFS CSV files. Optional.
db database instance An existing database instance to use instead of relying on node-gtfs to connect. Optional.
downloadTimeout integer The number of milliseconds to wait before throwing an error when downloading GTFS. Optional.
exportPath string A path to a directory to put exported GTFS files. Optional, defaults to gtfs-export/<agency_name>.
gtfsRealtimeExpirationSeconds integer Amount of time in seconds to allow GTFS-Realtime data to be stored in database before allowing to be deleted. Optional, defaults to 0.
ignoreDuplicates boolean Whether or not to ignore unique constraints on ids when importing GTFS, such as trip_id, calendar_id. Optional, defaults to false.
ignoreErrors boolean Whether or not to ignore errors during the import process. If true, when importing multiple agencies, failed agencies will be skipped. Optional, defaults to false.
sqlitePath string A path to an SQLite database. Optional, defaults to using an in-memory database.
verbose boolean Whether or not to print output to the console. Optional, defaults to true.

agencies

{Array} Specify the GTFS files to be imported in an agencies array. GTFS files can be imported via a url or a local path.

For GTFS files that contain more than one agency, you only need to list each GTFS file once in the agencies array, not once per agency that it contains.

agencies options

option type description
url string The URL to a zipped GTFS file. Required if path not present.
path string A path to a zipped GTFS file or a directory of unzipped .txt files. Required if url is not present.
headers object An object of HTTP headers in key:value format to use when fetching GTFS from the url specified. Optional.
prefix string A prefix to be added to every ID field maintain uniqueness when importing multiple GTFS from multiple agencies. Optional.
exclude array An array of GTFS file names (without .txt) to exclude when importing. Optional.
realtimeAlerts object An object containing a url field for GTFS-Realtime alerts and a headers field in key:value format to use when fetching GTFS-Realtime data. Optional.
realtimeTripUpdates object An object containing a url field for GTFS-Realtime trip updates and a headers field in key:value format to use when fetching GTFS-Realtime data. Optional.
realtimeVehiclePositions object An object containing a url field for GTFS-Realtime vehicle positions and a headers field in key:value format to use when fetching GTFS-Realtime data. Optional.
  • Specify a url to download GTFS:
{
  "agencies": [
    {
      "url": "https://www.bart.gov/dev/schedules/google_transit.zip"
    }
  ]
}
  • Specify a download URL with custom headers using the headers field:
{
  "agencies": [
    {
      "url": "https://www.bart.gov/dev/schedules/google_transit.zip",
      "headers": {
        "Content-Type": "application/json",
        "Authorization": "bearer 1234567890"
      }
    }
  ]
}
  • Specify a path to a zipped GTFS file:
{
  "agencies": [
    {
      "path": "/path/to/the/gtfs.zip"
    }
  ]
}
  • Specify a path to an unzipped GTFS file:
{
  "agencies": [
    {
      "path": "/path/to/the/unzipped/gtfs/"
    }
  ]
}
  • If you don't want all GTFS files to be imported, you can specify an array of files to exclude. This can save a lot of time for larger GTFS.
{
  "agencies": [
    {
      "path": "/path/to/the/unzipped/gtfs/",
      "exclude": ["shapes", "stops"]
    }
  ]
}
  • Specify urls for GTFS-Realtime updates. realtimeAlerts, realtimeTripUpdates and realtimeVehiclePositions fields accept an object with a url and optional headers field to specify HTTP headers to include with the request, usually for authorization purposes.
{
  "agencies": [
    {
      "url": "https://www.bart.gov/dev/schedules/google_transit.zip",
      "realtimeAlerts": {
        "url": "https://api.bart.gov/gtfsrt/alerts.aspx",
        "headers": {
          "Authorization": "bearer 123456789"
        }
      },
      "realtimeTripUpdates": {
        "url": "https://api.bart.gov/gtfsrt/tripupdate.aspx",
        "headers": {
          "Authorization": "bearer 123456789"
        }
      },
      "realtimeVehiclePositions": {
        "url": "https://api.bart.gov/gtfsrt/vehiclepositions.aspx",
        "headers": {
          "Authorization": "bearer 123456789"
        }
      }
    }
  ]
}
  • Specify multiple agencies to be imported into the same database
{
  "agencies": [
    {
      "path": "/path/to/the/gtfs.zip"
    },
    {
      "path": "/path/to/the/othergtfs.zip"
    }
  ]
}
  • When importing multiple agencies their IDs may overlap. Specify a prefix to be added to every ID field to maintain uniqueness.
{
  "agencies": [
    {
      "path": "/path/to/the/gtfs.zip",
      "prefix": "A"
    },
    {
      "path": "/path/to/the/othergtfs.zip",
      "prefix": 10000
    }
  ]
}

csvOptions

{Object} Add options to be passed to csv-parse with the key csvOptions. This is an optional parameter.

For instance, if you wanted to skip importing invalid lines in the GTFS file:

    "csvOptions": {
      "skip_lines_with_error": true
    }

See full list of options.

db

{Database Instance} When passing configuration to importGtfs in javascript, you can pass a db parameter with an existing database instance. This is not possible using a json configuration file Optional.

// Using better-sqlite3 to open database
import { importGtfs } from 'gtfs';
import Database from 'better-sqlite3';

const db = new Database('/path/to/database');

importGtfs({
  agencies: [
    {
      path: '/path/to/the/unzipped/gtfs/',
    },
  ],
  db: db,
});
// Using `openDb` from node-gtfs to open database
import { importGtfs, openDb } from 'gtfs';

const db = openDb({
  sqlitePath: '/path/to/database',
});

importGtfs({
  agencies: [
    {
      path: '/path/to/the/unzipped/gtfs/',
    },
  ],
  db: db,
});

downloadTimeout

{Integer} A number of milliseconds to wait when downloading GTFS before throwing an error. Optional.

{
  "agencies": [
    {
      "path": "/path/to/the/unzipped/gtfs/"
    }
  ],
  "downloadTimeout": 5000
}

exportPath

{String} A path to a directory to put exported GTFS files. If the directory does not exist, it will be created. Used when running gtfs-export script or exportGtfs(). Optional, defaults to gtfs-export/<agency_name> where <agency_name> is a sanitized, snake-cased version of the first agency_name in agency.txt.

{
  "agencies": [
    {
      "path": "/path/to/the/unzipped/gtfs/"
    }
  ],
  "exportPath": "~/path/to/export/gtfs"
}

gtfsRealtimeExpirationSeconds

{Integer} Amount of time in seconds to allow GTFS-Realtime data to be stored in database before allowing to be deleted. Defaults to 0 (old GTFS-Realtime is deleted immediately when new data arrives). Note that if new data arrives for the same trip update, vehicle position or service alert before the expiration time, it will overwrite the existing data. The gtfsRealtimeExpirationSeconds only affects when data is deleted.

{
  "agencies": [
    {
      "url": "https://www.bart.gov/dev/schedules/google_transit.zip",
      "realtimeAlerts": {
        "url": "https://api.bart.gov/gtfsrt/alerts.aspx"
      },
      "realtimeTripUpdates": {
        "url": "https://api.bart.gov/gtfsrt/tripupdate.aspx"
      },
      "realtimeVehiclePositions": {
        "url": "https://api.bart.gov/gtfsrt/vehiclepositions.aspx"
      }
    }
  ],
  "gtfsRealtimeExpirationSeconds": false
}

ignoreDuplicates

{Boolean} If you don't want node-GTFS to throw an error when it encounters a duplicate id on GTFS import. If true, it will skip importing duplicate records where unique constraints are violated, such astrip_id, stop_id, calendar_id. Useful if importing GTFS from multiple sources into one SQlite database that share routes or stops. Defaults to false.

{
  "agencies": [
    {
      "path": "/path/to/the/unzipped/gtfs/"
    }
  ],
  "ignoreDuplicates": false
}

ignoreErrors

{Boolean} When importing GTFS from multiple agencies, if you don't want node-GTFS to throw an error and instead skip failed GTFS importants proceed to the next agency. Defaults to false.

{
  "agencies": [
    {
      "path": "/path/to/the/unzipped/gtfs/"
    }
  ],
  "ignoreErrors": true
}

sqlitePath

{String} A path to an SQLite database. Optional, defaults to using an in-memory database with a value of :memory:.

    "sqlitePath": "/dev/sqlite/gtfs"

verbose

{Boolean} If you don't want the import script to print any output to the console, you can set verbose to false. Defaults to true.

{
  "agencies": [
    {
      "path": "/path/to/the/unzipped/gtfs/"
    }
  ],
  "verbose": false
}

If you want to route logs to a custom function, you can pass a function that takes a single text argument as logFunction. This can't be defined in config.json but instead passed in a config object to importGtfs(). For example:

import { importGtfs } from 'gtfs';

const config = {
  agencies: [
    {
      url: 'https://www.bart.gov/dev/schedules/google_transit.zip',
      exclude: ['shapes'],
    },
  ],
  logFunction: function (text) {
    // Do something with the logs here, like save it or send it somewhere
    console.log(text);
  },
};

await importGtfs(config);

gtfs-import Script

The gtfs-import script reads from a JSON configuration file and imports the GTFS files specified to a SQLite database. Read more on setting up your configuration file.

Run the gtfs-import script from command-line

gtfs-import

By default, it will look for a config.json file in the project root. To specify a different path for the configuration file:

gtfs-import --configPath /path/to/your/custom-config.json

Use importGtfs script in code

Use importGtfs() in your code to run an import of a GTFS file specified in a config.json file.

import { importGtfs } from 'gtfs';
import { readFile } from 'fs/promises';
import path from 'node:path';

const config = JSON.parse(
  await readFile(path.join(import.meta.dirname, 'config.json'))
);

await importGtfs(config);

Configuration can be a JSON object in your code

import { importGtfs } from 'gtfs';

const config = {
  sqlitePath: '/dev/sqlite/gtfs',
  agencies: [
    {
      url: 'https://www.bart.gov/dev/schedules/google_transit.zip',
      exclude: ['shapes'],
    },
  ],
};

await importGtfs(config);

gtfsrealtime-update Script

The gtfsrealtime-update script requests GTFS-Realtime data and importings into a SQLite database. GTFS-Realtime data can compliment GTFS Static data. Read more about GTFS-Realtime configuration.

Run the gtfsrealtime-update script from command-line

gtfsrealtime-update

By default, it will look for a config.json file in the project root. To specify a different path for the configuration file:

gtfsrealtime-update --configPath /path/to/your/custom-config.json

Use updateGtfsRealtime script in code

Use updateGtfsRealtime() in your code to run an update of a GTFS-Realtime data specified in a config.json file.

import { updateGtfsRealtime } from 'gtfs';
import { readFile } from 'fs/promises';
import path from 'node:path';

const config = JSON.parse(
  await readFile(path.join(import.meta.dirname, 'config.json'))
);

await updateGtfsRealtime(config);

gtfs-export Script

The gtfs-export script reads from a JSON configuration file and exports data in GTFS format from a SQLite database. Read more on setting up your configuration file.

This could be used to export a GTFS file from SQLite after changes have been made to the data in the database manually.

Make sure to import GTFS data into SQLite first

Nothing will be exported if there is no data to export. See the GTFS import script.

Run the gtfs-export script from Command-line

gtfs-export

By default, it will look for a config.json file in the project root. To specify a different path for the configuration file:

gtfs-export --configPath /path/to/your/custom-config.json

Command-Line options

Specify path to config JSON file

You can specify the path to a config file to be used by the export script.

gtfs-export --configPath /path/to/your/custom-config.json

Show help

Show all command-line options

gtfs-export --help

Use exportGtfs script in code

Use exportGtfs() in your code to run an export of a GTFS file specified in a config.json file.

import { exportGtfs } from 'gtfs';

const config = {
  sqlitePath: '/dev/sqlite/gtfs',
  agencies: [
    {
      url: 'https://www.bart.gov/dev/schedules/google_transit.zip',
      exclude: ['shapes'],
    },
  ],
};

await exportGtfs(config);

Query Methods

This library includes many methods you can use in your project to query GTFS data. In addition to standard static GTFS, node-gtfs supports the following extensions to GTFS:

There are also methods for retrieving stops and shapes in geoJSON format.

Most query methods accept three optional arguments: query, fields, sortBy and options.

For more advanced queries, you can use advancedQuery or raw SQL queries using query method from better-sqlite3.

Database Setup

To use any of the query methods, first open the database using openDb before making any queries:

import { openDb } from 'gtfs';
import { readFile } from 'fs/promises';
import path from 'node:path';

const config = JSON.parse(
  await readFile(path.join(import.meta.dirname, 'config.json'))
);

const db = openDb(config);

If you no longer need a database (especially if using an in-memory database) you can use closeDb:

import { closeDb, openDb } from 'gtfs';
const db = openDb(config);

// Do some stuff here

// Close database connection when done.
closeDb(db);

Deleting a Database

You can use deleteDb to delete a sqlite3 database from the filesystem.

import { deleteDb, openDb } from 'gtfs';
const db = openDb(config);

// Do some stuff here

// Delete the database
deleteDb(db);

Examples

For example, to get a list of all routes with just route_id, route_short_name and route_color sorted by route_short_name:

import { closeDb, openDb, getRoutes } from 'gtfs';
import { readFile } from 'fs/promises';
import path from 'node:path';

const config = JSON.parse(
  await readFile(path.join(import.meta.dirname, 'config.json'))
);

const db = openDb(config);
const routes = getRoutes(
  {}, // No query filters
  ['route_id', 'route_short_name', 'route_color'], // Only return these fields
  [['route_short_name', 'ASC']], // Sort by this field and direction
  { db: db }, // Options for the query. Can specify which database to use if more than one are open
);

closeDb(db);

To get a list of all trip_ids for a specific route:

import { closeDb, openDb, getTrips } from 'gtfs';
import { readFile } from 'fs/promises';
import path from 'node:path';

const config = JSON.parse(
  await readFile(path.join(import.meta.dirname, 'config.json'))
);

const db = openDb(config);
const trips = getTrips(
  {
    route_id: '123',
  },
  ['trip_id'],
);

closeDb(db);

To get a few stops by specific stop_ids:

import { closeDb, openDb, getStops } from 'gtfs';
import { readFile } from 'fs/promises';
import path from 'node:path';

const config = JSON.parse(
  await readFile(path.join(import.meta.dirname, 'config.json'))
);
const db = openDb(config);
const stops = getStops(
  {
    stop_id: [
      '123',
      '234'
      '345'
    ]
  }
);

closeDb(db);

Static GTFS Files

getAgencies(query, fields, sortBy, options)

Returns an array of agencies that match query parameters. Details on agency.txt

import { getAgencies } from 'gtfs';

// Get all agencies
const agencies = getAgencies();

// Get a specific agency
const agencies = getAgencies({
  agency_id: 'caltrain',
});

getAreas(query, fields, sortBy, options)

Returns an array of areas that match query parameters. Details on areas.txt

import { getAreas } from 'gtfs';

// Get all areas
const areas = getAreas();

// Get a specific area
const areas = getAreas({
  area_id: 'area1',
});

getAttributions(query, fields, sortBy, options)

Returns an array of attributions that match query parameters. Details on attributions.txt

import { getAttributions } from 'gtfs';

// Get all attributions
const attributions = getAttributions();

// Get a specific attribution
const attributions = getAttributions({
  attribution_id: '123',
});

getBookingRules(query, fields, sortBy, options)

Returns an array of booking rules that match query parameters. Details on booking_rules.txt

import { getBookingRules } from 'gtfs';

// Get all booking rules
const bookingRules = getBookingRules();

// Get a specific booking rule
const bookingRules = getBookingRules({
  booking_rule_id: '1234',
});

getRoutes(query, fields, sortBy, options)

Returns an array of routes that match query parameters. Details on routes.txt

import { getRoutes } from 'gtfs';

// Get all routes, sorted by route_short_name
const routes = getRoutes({}, [], [['route_short_name', 'ASC']]);

// Get a specific route
const routes = getRoutes({
  route_id: 'Lo-16APR',
});

/*
 * `getRoutes` allows passing a `stop_id` as part of the query. This will
 * query stoptimes and trips to find all routes that serve that `stop_id`.
 */
const routes = getRoutes(
  {
    stop_id: '70011',
  },
  [],
  [['stop_name', 'ASC']],
);

getStops(query, fields, sortBy, options)

Returns an array of stops that match query parameters. Details on stops.txt

import { getStops } from 'gtfs';

// Get all stops
const stops = getStops();

// Get a specific stop by stop_id
const stops = getStops({
  stop_id: '70011',
});

/*
 * `getStops` allows passing a `route_id` in the query and it will
 * query trips and stoptimes to find all stops served by that `route_id`.
 */
const stops = getStops({
  route_id: 'Lo-16APR',
});

/*
 * `getStops` allows passing a `trip_id` in the query and it will query
 * stoptimes to find all stops on that `trip_id`.
 */
const stops = getStops({
  trip_id: '37a',
});

/*
 * `getStops` allows passing a `shape_id` in the query and it will query
 * trips and stoptimes to find all stops that use that `shape_id`.
 */
const stops = getStops({
  shape_id: 'cal_sf_tam',
});

/*
 * `getStops` allows passing a `bounding_box_side_m` value in the options
 * parameter object. If included, it will return all stops within a square
 * bounding box around the `stop_lat` and `stop_lon` parameters passed to
 * the query using the size in meters specified.
 */
const stops = getStops(
  {
    stop_lat: 37.58764,
    stop_lon: -122.36265,
  },
  [],
  [],
  {
    bounding_box_side_m: 1000
  }
);

getStopsAsGeoJSON(query, options)

Returns geoJSON object of stops that match query parameters. Stops will include all properties of each stop from stops.txt and stop_attributes.txt if present. All valid queries for getStops() work for getStopsAsGeoJSON().

import { getStopsAsGeoJSON } from 'gtfs';

// Get all stops for an agency as geoJSON
const stopsGeojson = getStopsAsGeoJSON();

// Get all stops for a specific route as geoJSON
const stopsGeojson = getStopsAsGeoJSON({
  route_id: 'Lo-16APR',
});

// Get all stops within a 1000m bounding box as geoJSON
const stopsGeojson = getStopsAsGeoJSON(
  {
    stop_lat: 37.58764,
    stop_lon: -122.36265,
  },
  {
    bounding_box_side_m: 1000,
  },
);

getStoptimes(query, fields, sortBy, options)

Returns an array of stop_times that match query parameters. Details on stop_times.txt

import { getStoptimes } from 'gtfs';

// Get all stoptimes
const stoptimes = getStoptimes();

// Get all stoptimes for a specific stop
const stoptimes = getStoptimes({
  stop_id: '70011',
});

// Get all stoptimes for a specific trip, sorted by stop_sequence
const stoptimes = getStoptimes(
  {
    trip_id: '37a',
  },
  [],
  [['stop_sequence', 'ASC']],
);

// Get all stoptimes for a specific stop and service_id
const stoptimes = getStoptimes({
  stop_id: '70011',
  service_id: 'CT-16APR-Caltrain-Weekday-01',
});

/*
 * `getStoptimes` allows passing a `date` in the query to return
 * only stoptimes for a specific day.
 */
const stoptimes = getStoptimes({
  stop_id: '70011',
  date: 20160704
});

/*
 * `getStoptimes` allows passing a `start_time` and/or and 
 * `end_time` in the query to return only stoptimes after 
 * start_time and before end_time. This can be combined with the 
 * `date` parameter to get upcoming stoptimes
 */
const stoptimes = getStoptimes({
  stop_id: '70011',
  date: 20160704,
  start_time: '11:30:00',
  end_time: '11:45:00'
});

getTrips(query, fields, sortBy, options)

Returns an array of trips that match query parameters. Details on trips.txt

import { getTrips } from 'gtfs';

// Get all trips
const trips = getTrips();

// Get trips for a specific route and direction
const trips = getTrips({
  route_id: 'Lo-16APR',
  direction_id: 0
});

// Get trips for direction '' or null
const trips = getTrips({
  route_id: 'Lo-16APR',
  direction_id: null
});

// Get trips for a specific route and direction limited by a service_id
const trips = getTrips({
  route_id: 'Lo-16APR',
  direction_id: 0,
  service_id: '
});

getShapes(query, fields, sortBy, options)

Returns an array of shapes that match query parameters. Details on shapes.txt

import { getShapes } from 'gtfs';

// Get all shapes for an agency
const shapes = getShapes();

/*
 * `getShapes` allows passing a `route_id` in the query and it will query
 * trips to find all shapes served by that `route_id`.
 */
const shapes = getShapes({
  route_id: 'Lo-16APR',
});

/*
 * `getShapes` allows passing a `trip_id` in the query and it will query
 * trips to find all shapes served by that `trip_id`.
 */
const shapes = getShapes({
  trip_id: '37a',
});

/*
 * `getShapes` allows passing a `service_id` in the query and it will query
 * trips to find all shapes served by that `service_id`.
 */
const shapes = getShapes({
  service_id: 'CT-16APR-Caltrain-Sunday-02',
});

getShapesAsGeoJSON(query, options)

Returns a geoJSON object of shapes that match query parameters. Shapes will include all properties of each route from routes.txt and route_attributes.txt if present. All valid queries for getShapes() work for getShapesAsGeoJSON().

import { getShapesAsGeoJSON } from 'gtfs';

// Get geoJSON of all routes in an agency
const shapesGeojson = getShapesAsGeoJSON();

// Get geoJSON of shapes for a specific route
const shapesGeojson = getShapesAsGeoJSON({
  route_id: 'Lo-16APR',
});

// Get geoJSON of shapes for a specific trip
const shapesGeojson = getShapesAsGeoJSON({
  trip_id: '37a',
});

// Get geoJSON of shapes for a specific `service_id`
const shapesGeojson = getShapesAsGeoJSON({
  service_id: 'CT-16APR-Caltrain-Sunday-02',
});

// Get geoJSON of shapes for a specific `shape_id`
const shapesGeojson = getShapesAsGeoJSON({
  shape_id: 'cal_sf_tam',
});

getCalendars(query, fields, sortBy, options)

Returns an array of calendars that match query parameters. Details on calendar.txt

import { getCalendars } from 'gtfs';

// Get all calendars for an agency
const calendars = getCalendars();

// Get calendars for a specific `service_id`
const calendars = getCalendars({
  service_id: 'CT-16APR-Caltrain-Sunday-02',
});

getServiceIdsByDate(date, options)

Returns an array of service_ids for a specified date. It queries both calendars.txt and calendar_dates.txt to calculate which service_ids are effective for that date, including exceptions. The date field is an integer in yyyymmdd format.

import { getServiceIdsByDate } from 'gtfs';

// Get service_ids for a specifc date
const serviceIds = getServiceIdsByDate(20240704);

getCalendarDates(query, fields, sortBy, options)

Returns an array of calendar_dates that match query parameters. Details on calendar_dates.txt

import { getCalendarDates } from 'gtfs';

// Get all calendar_dates for an agency
const calendarDates = getCalendarDates();

// Get calendar_dates for a specific `service_id`
const calendarDates = getCalendarDates({
  service_id: 'CT-16APR-Caltrain-Sunday-02',
});

getFareAttributes(query, fields, sortBy, options)

Returns an array of fare_attributes that match query parameters. Details on fare_attributes.txt

import { getFareAttributes } from 'gtfs';

// Get all `fare_attributes` for an agency
const fareAttributes = getFareAttributes();

// Get `fare_attributes` for a specific `fare_id`
const fareAttributes = getFareAttributes({
  fare_id: '123',
});

getFareLegRules(query, fields, sortBy, options)

Returns an array of fare_leg_rules that match query parameters. Details on fare_leg_rules.txt

import { getFareLegRules } from 'gtfs';

// Get all fare leg rules
const fareLegRules = getFareLegRules();

// Get fare leg rules for a specific fare product
const fareLegRules = getFareLegRules({
  fare_product_id: 'product1',
});

getFareMedia(query, fields, sortBy, options)

Returns an array of fare_media that match query parameters. Details on fare_media.txt

import { getFareMedia } from 'gtfs';

// Get all fare media
const getFareMedia = getFareMedia();

// Get a specific fare media
const fareMedia = getFareMedia({
  fare_media_id: 'media1',
});

getFareProducts(query, fields, sortBy, options)

Returns an array of fare_products that match query parameters. Details on fare_products.txt

import { getFareProducts } from 'gtfs';

// Get all fare products
const fareProducts = getFareProducts();

// Get a specific fare product
const fareProducts = getFareProducts({
  fare_product_id: 'product1',
});

getFareRules(query, fields, sortBy, options)

Returns an array of fare_rules that match query parameters. Details on fare_rules.txt

import { getFareRules } from 'gtfs';

// Get all `fare_rules` for an agency
const fareRules = getFareRules();

// Get fare_rules for a specific route
const fareRules = getFareRules({
  route_id: 'Lo-16APR',
});

getFareTransferRules(query, fields, sortBy, options)

Returns an array of fare_transfer_rules that match query parameters. Details on fare_transfer_rules.txt

import { getFareTransferRules } from 'gtfs';

// Get all fare transfer rules
const fareTransferRules = getFareTransferRules();

// Get a all fare transfer rules for a specific fare product
const fareTransferRules = getFareTransferRules({
  fare_product_id: 'product1',
});

getFeedInfo(query, fields, sortBy, options)

Returns an array of feed_info that match query parameters. Details on feed_info.txt

import { getFeedInfo } from 'gtfs';

// Get feed_info
const feedInfo = getFeedInfo();

getFrequencies(query, fields, sortBy, options)

Returns an array of frequencies that match query parameters. Details on frequencies.txt

import { getFrequencies } from 'gtfs';

// Get all frequencies
const frequencies = getFrequencies();

// Get frequencies for a specific trip
const frequencies = getFrequencies({
  trip_id: '1234',
});

getLevels(query, fields, sortBy, options)

Returns an array of levels that match query parameters. Details on levels.txt

import { getLevels } from 'gtfs';

// Get all levels
const levels = getLevels();

getLocationGroups(query, fields, sortBy, options)

Returns an array of location groups that match query parameters. Details on location_groups.txt

import { getLocationGroups } from 'gtfs';

// Get all location groups
const locationGroups = getLocationGroups();

// Get a specific location group
const locationGroups = getLocationGroups({
  location_group_id: '1234',
});

getLocationGroupStops(query, fields, sortBy, options)

Returns an array of location group stops that match query parameters. Details on location_group_stops.txt

import { getLocationGroupStops } from 'gtfs';

// Get all location group stops
const locationGroupStops = getLocationGroupStops();

// Get location group stops for a specific stop_id
const locationGroups = getLocationGroupStops({
  stop_id: '1234',
});

getLocations(query, fields, sortBy, options)

Returns an array of locations that match query parameters. Each location is text that can be parsed into a geojson object. Details on locations.geojson

import { getLocations } from 'gtfs';

// Get all locations
const locations = getLocations();

getPathways(query, fields, sortBy, options)

Returns an array of pathways that match query parameters. Details on pathways.txt

import { getPathways } from 'gtfs';

// Get all pathways
const pathways = getPathways();

getTimeframes(query, fields, sortBy, options)

Returns an array of timeframes that match query parameters. Details on timeframes.txt

import { getTimeframes } from 'gtfs';

// Get all timeframes
const timeframes = getTimeframes();

getTransfers(query, fields, sortBy, options)

Returns an array of transfers that match query parameters. Details on transfers.txt

import { getTransfers } from 'gtfs';

// Get all transfers
const transfers = getTransfers();

// Get transfers for a specific stop
const transfers = getTransfers({
  from_stop_id: '1234',
});

getTranslations(query, fields, sortBy, options)

Returns an array of translations that match query parameters. Details on translations.txt

import { getTranslations } from 'gtfs';

// Get all translations
const translations = getTranslations();

getStopAreas(query, fields, sortBy, options)

Returns an array of stop_areas that match query parameters. Details on stop_areas.txt

import { getStopAreas } from 'gtfs';

// Get all stop areas
const stopAreas = getStopAreas();

getNetworks(query, fields, sortBy, options)

Returns an array of networks that match query parameters. Details on networks.txt

import { getNetworks } from 'gtfs';

// Get all networks
const networks = getNetworks();

// Get networks for a specific network_id
const networks = getNetworks({
  network_id: '1234',
});

getRouteNetworks(query, fields, sortBy, options)

Returns an array of route_networks that match query parameters. Details on route_networks.txt

import { getRouteNetworks } from 'gtfs';

// Get all route_networks
const routeNetworks = getRouteNetworks();

// Get route_networks for a specific network_id
const routeNetworks = getRouteNetworks({
  network_id: '1234',
});

GTFS-Timetables files

getTimetables(query, fields, sortBy, options)

Returns an array of timetables that match query parameters. This is for the non-standard timetables.txt file used in GTFS-to-HTML. Details on timetables.txt

import { getTimetables } from 'gtfs';

// Get all timetables for an agency
const timetables = getTimetables();

// Get a specific timetable
const timetables = getTimetables({
  timetable_id: '1',
});

getTimetableStopOrders(query, fields, sortBy, options)

Returns an array of timetable_stop_orders that match query parameters. This is for the non-standard timetable_stop_order.txt file used in GTFS-to-HTML. Details on timetable_stop_order.txt

import { getTimetableStopOrders } from 'gtfs';

// Get all timetable_stop_orders
const timetableStopOrders = getTimetableStopOrders();

// Get timetable_stop_orders for a specific timetable
const timetableStopOrders = getTimetableStopOrders({
  timetable_id: '1',
});

getTimetablePages(query, fields, sortBy, options)

Returns an array of timetable_pages that match query parameters. This is for the non-standard timetable_pages.txt file used in GTFS-to-HTML. Details on timetable_pages.txt

import { getTimetablePages } from 'gtfs';

// Get all timetable_pages for an agency
const timetablePages = getTimetablePages();

// Get a specific timetable_page
const timetablePages = getTimetablePages({
  timetable_page_id: '2',
});

getTimetableNotes(query, fields, sortBy, options)

Returns an array of timetable_notes that match query parameters. This is for the non-standard timetable_notes.txt file used in GTFS-to-HTML. Details on timetable_notes.txt

import { getTimetableNotes } from 'gtfs';

// Get all timetable_notes for an agency
const timetableNotes = getTimetableNotes();

// Get a specific timetable_note
const timetableNotes = getTimetableNotes({
  note_id: '1',
});

getTimetableNotesReferences(query, fields, sortBy, options)

Returns an array of timetable_notes_references that match query parameters. This is for the non-standard timetable_notes_references.txt file used in GTFS-to-HTML. Details on timetable_notes_references.txt

import { getTimetableNotesReferences } from 'gtfs';

// Get all timetable_notes_references for an agency
const timetableNotesReferences = getTimetableNotesReferences();

// Get all timetable_notes_references for a specific timetable
const timetableNotesReferences = getTimetableNotesReferences({
  timetable_id: '4',
});

GTFS-Realtime

In order to use GTFS-Realtime query methods, you must first run the GTFS-Realtime update script or function to pull data into your database.

getServiceAlerts(query, fields, sortBy, options)

Returns an array of GTFS Realtime service alerts that match query parameters. Note that this does not refresh the data from GTFS-Realtime feeds, it only fetches what is stored in the database. In order to fetch the latest service alerts from GTFS-Realtime feeds and store in your database, use the GTFS-Realtime update script or function.

More details on Service Alerts

import { getServiceAlerts } from 'gtfs';

// Get service alerts
const serviceAlerts = getServiceAlerts();

getTripUpdates(query, fields, sortBy, options)

Returns an array of GTFS Realtime trip updates that match query parameters. Note that this does not refresh the data from GTFS-Realtime feeds, it only fetches what is stored in the database. In order to fetch the latest trip updates from GTFS-Realtime feeds and store in your database, use the GTFS-Realtime update script or function.

More details on Trip Updates

import { getTripUpdates } from 'gtfs';

// Get all trip updates
const tripUpdates = getTripUpdates();

getStopTimeUpdates(query, fields, sortBy, options)

Returns an array of GTFS Realtime stop time updates that match query parameters. Note that this does not refresh the data from GTFS-Realtime feeds, it only fetches what is stored in the database. In order to fetch the latest stop time updates from GTFS-Realtime feeds and store in your database, use the GTFS-Realtime update script or function.

More details on Stop Time Updates

import { getStopTimeUpdates } from 'gtfs';

// Get all stop time updates
const stopTimeUpdates = getStopTimeUpdates();

getVehiclePositions(query, fields, sortBy, options)

Returns an array of GTFS Realtime vehicle positions that match query parameters. Note that this does not refresh the data from GTFS-Realtime feeds, it only fetches what is stored in the database. In order to fetch the latest vehicle positions from GTFS-Realtime feeds and store in your database, use the GTFS-Realtime update script or function.

More details on Vehicle Positions

import { getVehiclePositions } from 'gtfs';

// Get all vehicle position data
const vehiclePositions = getVehiclePositions();

GTFS+ Files

getCalendarAttributes(query, fields, sortBy, options)

Returns an array of calendar_attributes that match query parameters.

import { getCalendarAttributes } from 'gtfs';

// Get all calendar attributes
const calendarAttributes = getCalendarAttributes();

// Get calendar attributes for specific service
const calendarAttributes = getCalendarAttributes({
  service_id: '1234',
});

getDirections(query, fields, sortBy, options)

Returns an array of directions that match query parameters.

import { getDirections } from 'gtfs';

// Get all directions
const directions = getDirections();

// Get directions for a specific route
const directions = getDirections({
  route_id: '1234',
});

// Get directions for a specific route and direction
const directions = getDirections({
  route_id: '1234',
  direction_id: 1,
});

getRouteAttributes(query, fields, sortBy, options)

Returns an array of route_attributes that match query parameters.

import { getRouteAttributes } from 'gtfs';

// Get all route attributes
const routeAttributes = getRouteAttributes();

// Get route attributes for specific route
const routeAttributes = getRouteAttributes({
  route_id: '1234',
});

getStopAttributes(query, fields, sortBy, options)

Returns an array of stop_attributes that match query parameters.

import { getStopAttributes } from 'gtfs';

// Get all stop attributes
const stopAttributes = getStopAttributes();

// Get stop attributes for specific stop
const stopAttributes = getStopAttributes({
  stop_id: '1234',
});

GTFS-Ride Files

See full documentation of GTFS Ride.

getBoardAlights(query, fields, sortBy, options)

Returns an array of board_alight that match query parameters. Details on board_alight.txt

import { getBoardAlights } from 'gtfs';

// Get all board_alight
const boardAlights = getBoardAlights();

// Get board_alight for a specific trip
const boardAlights = getBoardAlights({
  trip_id: '123',
});

getRideFeedInfo(query, fields, sortBy, options)

Returns an array of ride_feed_info that match query parameters. Details on ride_feed_info.txt

import { getRideFeedInfo } from 'gtfs';

// Get all ride_feed_info
const rideFeedInfos = getRideFeedInfo();

getRiderTrips(query, fields, sortBy, options)

Returns an array of rider_trip that match query parameters. Details on rider_trip.txt

import { getRiderTrips } from 'gtfs';

// Get all rider_trip
const riderTrips = getRiderTrips();

// Get rider_trip for a specific trip
const riderTrips = getRiderTrips({
  trip_id: '123',
});

getRidership(query, fields, sortBy, options)

Returns an array of ridership that match query parameters. Details on ridership.txt

import { getRidership } from 'gtfs';

// Get all ridership
const riderships = getRidership();

// Get ridership for a specific route
const riderships = getRidership({
  route_id: '123',
});

getTripCapacities(query, fields, sortBy, options)

Returns an array of trip_capacity that match query parameters. Details on trip_capacity.txt

import { getTripCapacities } from 'gtfs';

// Get all trip_capacity
const tripCapacities = getTripCapacities();

// Get trip_capacity for a specific trip
const tripCapacities = getTripCapacities({
  trip_id: '123',
});

Operational Data Standard (ODS) Files

getDeadheads(query, fields, sortBy, options)

Returns an array of deadheads that match query parameters. Details on deadheads.txt

import { getDeadheads } from 'gtfs';

// Get all deadheads
const deadheads = getDeadheads();

// Get deadheads for a specific block
const deadheads = getDeadheads({
  block_id: '123',
});

getDeadheadTimes(query, fields, sortBy, options)

Returns an array of deadhead_times that match query parameters. Details on deadhead_times.txt

import { getDeadheadTimes } from 'gtfs';

// Get all deadhead_times
const deadheadTimes = getDeadheadTimes();

// Get deadhead_times for a specific deadhead
const deadheadTimes = getDeadheadTimes({
  deadhead_id: '123',
});

getOpsLocations(query, fields, sortBy, options)

Returns an array of ops_locations that match query parameters. Details on ops_locations.txt

import { getOpsLocations } from 'gtfs';

// Get all ops_locations
const opsLocations = getOpsLocations();

// Get a specific ops_locations
const opsLocations = getOpsLocations({
  ops_location_id: '123',
});

getRunsPieces(query, fields, sortBy, options)

Returns an array of runs_pieces that match query parameters. Details on runs_pieces.txt

import { getRunsPieces } from 'gtfs';

// Get all runs_pieces
const runsPieces = getRunsPieces();

getRunEvents(query, fields, sortBy, options)

Returns an array of run_events that match query parameters. Details on run_events.txt

import { getRunEvents } from 'gtfs';

// Get all run_events
const runEvents = runEvents();

// Get a run_events for a specific piece
const runEvents = runEvents({
  piece_id: '123',
});

Other Non-standard GTFS Files

getTripsDatedVehicleJourneys(query, fields, sortBy, options)

Returns an array of trips_dated_vehicle_journey that match query parameters. This is for the non-standard trips_dated_vehicle_journey.txt file. Details on trips_dated_vehicle_journey.txt

import { getTripsDatedVehicleJourneys } from 'gtfs';

// Get all trips_dated_vehicle_journey
const tripsDatedVehicleJourneys = getTripsDatedVehicleJourneys();

Advanced Query Methods

advancedQuery(table, advancedQueryOptions)

Queries the database with support for table joins and custom tables and returns an array of data.

import { advancedQuery } from 'gtfs';

// Example `advancedQuery` joining stop_times with trips.
const advancedQueryOptions = {
  query: {
    'stop_times.trip_id': tripId,
  },
  fields: ['stop_times.trip_id', 'arrival_time'],
  join: [
    {
      type: 'INNER',
      table: 'trips',
      on: 'stop_times.trip_id=trips.trip_id',
    },
  ],
};

const stoptimes = advancedQuery('stop_times', advancedQueryOptions);

Raw SQLite Query

Use the openDb function to get the db object, and then use any query method from better-sqlite3 to query GTFS data.

import { openDb } from 'gtfs';
const db = openDb(config);

// Get a specific trip
const trip = db.prepare('SELECT * FROM trips WHERE trip_id = ?').get('123');

// Get all stops
const stops = db.prepare('SELECT * from stops').all();

// Get all calendar_ids for specific date
const calendarIds = db
  .prepare(
    'SELECT service_id from calendar WHERE start_date <= $date AND end_date >= $date'
  )
  .all({ date: 20150101 });

// Find all stops for route_id=18 by joining tables
const stopIds = db
  .prepare(
    'SELECT DISTINCT stops.stop_id from stops INNER JOIN stop_times ON stops.stop_id = stop_times.stop_id INNER JOIN trips on trips.trip_id = stop_times.trip_id WHERE trips.route_id = ?'
  )
  .all('18');

// Execute raw SQL
const sql = "DELETE FROM trips where trip_id = '329'";
db.exec(sql);

Contributing

Pull requests are welcome, as is feedback and reporting issues.

Tests

To run tests:

npm test

To run a specific test:

npm test -- get-stoptimes

更新日志

Changelog

All notable changes to this project will be documented in this file.

The format is based on Keep a Changelog, and this project adheres to Semantic Versioning.

[Unreleased]

Fixed

  • Correct Primary Key for fare_products.txt

Added

  • Add TIDES support

Updated

  • Dependency Updates

[4.17.3] - 2025-04-23

Updated

  • Use sqlite virtual columns for timestamp columns

[4.17.2] - 2025-04-17

Updated

  • Dependency Updates

Fixed

  • Make is_default_fare_category allowed to be blank in rider_categories.txt

[4.17.1] - 2025-03-29

Updated

  • Add prefix support for GTFS-realtime data
  • Batch insert GTFS-realtime data

[4.17.0] - 2025-03-27

BREAKING CHANGES

  • GTFS-Realtime Informed Entities:
    • Renamed table from service_alert_targets to service_alert_informed_entities
    • Changed GTFS-Realtime parsing defaults to false

Updated

  • Dependency Updates
  • Remove package-lock.json
  • Update to tsconfig.json

Fixed

  • Update Service Alert informed entities to add trip_id, direction_id and route_type fields
  • Updated GTFS-Realtime parsing to defaults=false to avoid 0 for empty int fields

[4.16.0] - 2025-03-21

Added

  • Support for rider_categories.txt

Updated

  • Dependency Updates

[4.15.15] - 2025-02-25

Updated

  • Dependency Updates

[4.15.14] - 2025-02-22

Fixed

  • Handle errors from formatGtfsLine

Updated

  • Dependency Updates

[4.15.13] - 2025-02-21

Updated

  • Return stops sorted by distance in getStops if bounding_box_side_m option present
  • Dependency Updates

[4.15.12] - 2025-01-08

Updated

  • Updated schema for service_alerts
  • Dependency Updates

Added

  • Add support for JSON column type

Fixed

  • Support for arrival/departure time after midnight

[4.15.11] - 2024-11-20

Updated

  • Updated GTFS-Realtime alerts fields
  • Dependency Updates

[4.15.10] - 2024-11-18

Updated

  • Dependency Updates

[4.15.9] - 2024-11-14

Updated

  • Updates to time columns and timestamp columns

Fixed

  • Better GTFS export for currency

[4.15.8] - 2024-11-14

Updated

  • GTFS export currency with correct number of decimal places

[4.15.7] - 2024-11-14

Updated

  • Types for gtfs-to-html files
  • Added primary key info for attributions.txt, fare_rules.txt, location_group_stops.txt, stop_areas.txt and timeframes.txt
  • Better column checks on imports
  • Don't exclude 'id' column from export

Fixed

  • Default logging verbose = true

[4.15.6] - 2024-11-05

Updated

  • Improve typescript support for results of each query method
  • Dependency Updates

Added

  • Better documentation for util functions

[4.15.5] - 2024-10-30

Fixed

  • Don't add prefixes to columns with null values

Updated

  • Dependency Updates

[4.15.4] - 2024-10-24

Updated

  • Improved logging functions
  • Dependency Updates

[4.15.3] - 2024-10-17

Added

  • Added new method getServiceIdsByDate
  • Added support for date, start_time and end_time in getStoptimes method

[4.15.2] - 2024-10-12

Updated

  • Export types for each GTFS file

[4.15.1] - 2024-10-06

Updated

  • Add elapsed time to output
  • Optimze formatGtfsLine function
  • Batch import into chunks

[4.15.0] - 2024-10-03

Updated

  • Faster GTFS Import (thanks to Mael)
  • Avoid array creation and string interpolation at each formatLine run
  • Add a new build-watch script
  • Memoize the calculate seconds from midnight and date functions
  • Create indexes after importing all the GTFS files
  • Avoid creating a new db connection for each importLines batch
  • Use sqlite's transaction method rather than batching prepare().run()
  • Fix getStops with bounding box test : order is not important
  • Move gtfs-realtime functions to new file
  • Dependency updates

[4.14.5] - 2024-09-23

Updated

  • Dependency Updates

[4.14.4] - 2024-09-13

Updated

  • Use ignoreErrors config for GTFS-Realtime fetching
  • Dependency Updates

[4.14.3] - 2024-09-12

Fixed

  • Better error handling for gtfsrealtime-update

[4.14.2] - 2024-09-11

Fixed

  • Fix for GTFS-Realtime vehicle positions import

Updated

  • Build before release-it

[4.14.1] - 2024-09-10

Changed

  • Update to fare_transfer_rules.txt model
  • Added types for all GTFS files

Updated

  • Dependency Updates

[4.14.0] - 2024-09-04

Changed

  • Changed config structure for GTFS-Realtime urls

Updated

  • Dependency Updates

[4.13.4] - 2024-08-05

Fixed

  • Correction to trips_dated_vehicle_journey

Updated

  • Changed model exports

[4.13.3] - 2024-08-03

Changed

  • getShapesAsGeoJSON returns MultiLineString

Updated

  • Omit undefined properties from geojson
  • Better geojson tests
  • Dependency Updates

[4.13.2] - 2024-07-27

Fixed

  • Better date import

Updated

  • Dependency Updates

[4.13.1] - 2024-07-12

Updated

  • Types for openDb function

[4.13.0] - 2024-07-10

Updated

  • Convert to Typescript
  • Move tests to Jest from Mocha
  • Dependency Updates

Fixed

  • Make attribution_id optional

[4.12.0] - 2024-06-17

Added

  • Support for service_id in getRoutes

Changed

  • Use tempy for temporary directory creation

[4.11.3] - 2024-06-13

Fixed

  • Better tests for locations.geojson
  • Handle unknown filename extensions in models

[4.11.2] - 2024-06-13

Added

Updated

  • Update sqlite type for all models
  • Dependency updates

[4.11.1] - 2024-06-05

Changed

  • Don't throw error on GTFS-Realtime import HTTP error

Updated

  • Remove recursive-copy module
  • Dependency updates

[4.11.0] - 2024-06-01

Added

Updated

  • Dependency updates

[4.10.4] - 2024-05-14

Updated

  • Improved error messages
  • Don't use pretty-error globally
  • Dependency updates

[4.10.3] - 2024-05-12

Added

  • Additional GTFS-RT vehiclePosition fields
  • deleteDb method

Updated

  • Dependency updates

[4.10.2] - 2024-04-02

Added

  • Better error message for gtfsrealtime-update command
  • Support additional fields for vehiclePosition GTFS-Realtime data

Updated

  • Dependency updates

[4.10.1] - 2024-03-29

Updated

  • Dependency updates

[4.10.0] - 2024-03-29

Added

[4.9.0] - 2024-03-12

Updated

  • Close DB if not :memory: from CLI after import

[4.8.0] - 2024-03-10

Added

  • ignoreErrors config option
  • downloadTimeout config option
  • db config option

[4.7.2] - 2024-03-05

Updated

  • Show info about ignoreDuplicates option when primary key constraint issue happens
  • Dependency updates

[4.7.1] - 2024-02-18

Updated

  • Support null arrival and departure in StopTimeUpdate

[4.7.0] - 2024-02-09

Added

  • Added bounding_box_side_m option to getStops and getStopsAsGeoJSON to find all stops within a bounding box.

Updated

  • Dependency updates

[4.6.0] - 2024-01-17

Changed

  • Renamed getStopTimesUpdates to getStopTimeUpdates.

Added

  • Added schedule_relationship, trip_start_time, direction_id and route_id fields to stop_time_updates and trip_updates tables.

Updated

  • Dependency updates

[4.5.1] - 2023-11-09

Updated

  • Dependency updates
  • Use path to types file instead of directory in package.json

Fixed

  • Exclude agency_id from export if empty

[4.5.0] - 2023-08-23

Updated

  • Increase maxInsertVariables to 32,000
  • Dependency updates

[4.4.3] - 2023-07-18

Updated

  • Dependency updates

[4.4.2] - 2023-07-08

Changed

  • Added index to stoptimes table for stop_id field
  • Updated node.js versions for tests

[4.4.1] - 2023-07-07

Changed

  • Use lint-staged instead of pretty-quick

Updated

  • Dependency updates

[4.4.0] - 2023-06-16

Changed

  • Pad leading zeros of timestamp columns

[4.3.2] - 2023-06-14

Updated

  • Dependency updates
  • node-csv relax_quotes config

[4.3.1] - 2023-06-06

Added

  • Ignore system directories within zip file

Updated

  • Dependency updates

[4.3.0] - 2023-05-04

Updated

  • Updated Readme to add closeDb documentation
  • Use node-stream-zip instead of unzipper

Added

  • Support for prefixes when importing multiple GTFS files

[4.2.0] - 2023-04-13

Updated

  • Add route_attributes to getShapesAsGeoJSON() function as geojson properties
  • Add stop_attributes to getStopsAsGeoJSON() function as geojson properties
  • Support for multi-column primary keys

[4.1.1] - 2023-04-12

Added

  • Support for GTFS+ Files

Updated

  • Dependency updates

[4.1.0] - 2023-02-25

Added

  • Support for Operational Data Standard (ODS) Files

Updated

  • Dependency updates

[4.0.3] - 2023-02-04

Changed

  • Updates to sqlite journal mode

Updated

  • Dependency updates

[4.0.2] - 2023-01-15

Changed

  • In getStopsAsGeoJSON only return stops that are part of a route.

Updated

  • Dependency updates

[4.0.1] - 2022-12-31

Updated

  • Update types info
  • Improved readme
  • Improved queries

[4.0.0] - 2022-12-30

Changed

  • Use better-sqlite3 library
  • Make all query methods synchronous
  • Remove runRawQuery (use Raw SQLite query instead)
  • Remove execRawQuery (use Raw SQLite query instead)
  • Remove getDb (use openDb instead)

[3.8.0] - 2022-12-22

Updated

  • Dependency updates
  • Add Node 18 tests

Changed

  • Make transfer_type not required in transfers.txt

[3.7.0] - 2022-11-17

Updated

  • Dependency updates

Added

  • Add ignoreDuplicates config option

[3.6.1] - 2022-11-08

Updated

  • Support for querying null values as part of an array

[3.6.0] - 2022-08-08

Added

  • GTFS Fares v2 and new transfers.txt fields

Updated

  • Dependency updates
  • Better examples in readme

[3.5.1] - 2022-07-26

Updated

  • Dependency updates

[3.5.0] - 2022-07-10

Updated

  • Use yoctocolors instead of chalk
  • Dependency updates

Fixed

  • Support untildify in sqlitePath config variable

[3.4.0] - 2022-06-12

Updated

  • Dependency updates
  • Documentation updates
  • Added default:, and source: keywords in the models to describe a default value and a source to transform from for GTFS-Realtime
  • Filtering all models belonging to GTFS-Realtime from import (but not export) in GTFS

Added

  • Added trips-dates-vehicle-journey.txt model
  • GTFS-Realtime Support for VehiclePositions, TripUpdates and ServiceAlerts
  • gtfsrealtime-update script - does selective refresh of only GTFS-Realtime data without deleting the database
  • updateGtfsRealtime() method - does selective refresh of only GTFS-Realtime data without deleting the database
  • getServiceAlerts(..), getStopTimesUpdates(..), getTripUpdates(..), and getVehicleLocations(..) added methods
  • advancedQuery, runRawQuery and execRawQuery methods to perform direct database queries

[3.3.1] - 2022-04-29

Added

  • Add support for querying by shape_id

[3.3.0] - 2022-04-26

Changed

  • Switched back to sqlite3 module

Updated

  • Dependency Updates

[3.2.5] - 2022-04-09

Updated

  • Dependency Updates

[3.2.4] - 2022-01-21

Updated

  • Dependency Updates

[3.2.3] - 2022-01-16

Added

  • Implemented case-insensitive columns on import

Updated

  • Dependency Updates

[3.2.2] - 2021-12-28

Updated

  • Dependency Updates

[3.2.1] - 2021-11-26

Updated

  • Updated sqlite3 dependency to use @vscode/sqlite3 for npm audit warning
  • Downgraded dtslint to 3.4.2 for npm audit warning

[3.2.0] - 2021-11-21

Added

  • Support for opening multiple sqlite databases
  • Basic TypeScript support (Matt Moran)

Updated

  • Readme updates
  • Dependency updates

[3.1.4] - 2021-10-17

Added

  • Husky and Prettier

Update

  • Downgraded node-sqlite3 library to released version

[3.1.3] - 2021-10-17

Added

  • Added release-it

Updated

  • Updated pinned node-sqlite3 library

[3.1.2] - 2021-09-25

Changed

  • Switch to recursive-copy library
  • Change pinned node-sqlite path

Updated

  • Dependency updates

[3.1.1] - 2021-09-013

Updated

[3.1.0] - 2021-08-02

Changed

  • Added database optimizations to greatly speed up import.

Fixed

  • Fix for timetable_notes_references schema

Updated

  • Dependency updates

[3.0.4] - 2021-06-23

Fixed

  • Fix for timetable_notes_references schema

Updated

  • Dependency updates

[3.0.3] - 2021-06-15

Updated

  • Dependency updates
  • Use eslint instead of xo

[3.0.2] - 2021-05-26

Fixed

  • Agency assignment for multi-agency GTFS in getShapesAsGeoJSON

Updated

  • Dependency updates

[3.0.1] - 2021-05-15

Fixed

  • Better error messages for missing config
  • Better error messages for invalid paths in config

Changed

  • Updated minimum node.js verstion to 14.17.0
  • Added github action tests for node 16
  • Dropped github action tests for node 12

Added

  • Tests for invalid path in config

Updated

  • Use copy-dir library
  • Dependency updates

[3.0.0] - 2021-05-13

Breaking Changes

  • Converted to ES Module
  • Renamed gtfs.import to gtfs.importGtfs
  • Renamed gtfs.export to gtfs.exportGtfs

Changed

  • Converted to ES Module

Updated

  • Dependency updates

[2.4.4] - 2021-05-07

Updated

  • Dependency updates

[2.4.3] - 2021-03-23

Added

  • Tests for GTFS-ride methods and models

Updated

  • Dependency updates

[2.4.2] - 2021-02-19

Fixed

  • Exclude timestamp fields from export

Updated

  • Dependency updates

[2.4.1] - 2021-02-09

Fixed

  • Updated transfers.txt model

Updated

  • Dependency updates

[2.4.0] - 2021-02-04

Added

  • Support for gtfsPath, gtfsUrl, exportPath and sqlitePath parameters for gtfs-import and gtfs-export scripts.

Changed

  • Removed need for agency_key in config.json - use sanitized version of first agency_name in agencies.txt

Updated

  • Dependency updates

[2.3.0] - 2021-01-20

Fixed

  • Update getDB test to handle unlimited serviceIds

Updated

  • Readme updates
  • Reorganize table creation
  • Better SQLite escaping
  • Dependency updates

Added

  • GTFS-ride models and methods
  • Support for exportPath config option
  • Use pluralize library

[2.2.4] - 2020-12-21

Updated

  • Updated github actions to test PRs and node 14.x
  • Better default sqlitePath
  • Detect TTY and use \n if not
  • Better error message when sqlitePath is invalid
  • Dependency updates

[2.2.3] - 2020-12-12

Updated

  • Better default GTFS in config-sample.json
  • Skip creating tables for excluded files

[2.2.2] - 2020-12-10

Updated

[2.2.1] - 2020-12-06

Updated

  • Improved shapes query

[2.2.0] - 2020-12-05

Updated

  • Use unzipper library to handle poorly formed zip files
  • Dependency updates

[2.1.1] - 2020-11-27

Fixed

  • Don't log missing non-standard GTFS files
  • Support for multiple agencies in one config file
  • Dependency updates

[2.1.0] - 2020-11-10

Added

  • Support for timetable_notes.txt and timetable_notes_references.txt

[2.0.9] - 2020-11-10

Changed

  • Expand model character limit
  • Don't require stop_name in stops.txt
  • Dependency updates

[2.0.8] - 2020-10-14

Changed

  • Improved validation on import

[2.0.7] - 2020-10-13

Added

  • Support for extended GTFS route types

[2.0.6] - 2020-10-13

Changed

  • Dependency updates

Added

  • Better error formatting
  • GTFS import validation and better errors

[2.0.5] - 2020-09-24

Fixed

  • Fix for selecting a single field.

[2.0.4] - 2020-09-20

Added

  • Support for non-standard directions.txt file.
  • Added getFareAttributes to README

[2.0.3] - 2020-09-14

Fixed

  • Fix for querying for null

[2.0.2] - 2020-09-06

Changed

  • Dependency updates

Fixed

  • Fix geojson property formatting

[2.0.1] - 2020-08-23

Added

  • Updated model fields to latest GTFS spec
  • Test for gtfs.getDb()
  • Improved geoJSON generation

[2.0.0] - 2020-08-20

Changed

  • Switched to SQLite
  • Breaking changes for all queries
  • Updated documentation

[1.10.4] - 2020-07-28

Added

  • start_time and end_time fields in timetables.txt

[1.10.3] - 2020-07-15

Added

  • Improved mongo connection documentation

Fixed

  • Dependency updates

[1.10.2] - 2020-06-08

Added

  • Config option csvOptions to pass options to csv-parse.

[1.10.1] - 2020-05-10

Fixed

  • Support for zipped GTFS files with subdirectories

[1.10.0] - 2020-04-20

Added

  • Support for exporting GTFS zip files

[1.9.1] - 2019-08-09

Changed

  • Better projections on all queries

[1.9.0] - 2019-08-06

Added

  • dataExpireAfterSeconds config option
  • created_at field on each document

Fixed

  • Removed invalid required fields from models
  • Removed date_last_updated field from agency

[1.8.9] - 2019-08-06

Changed

  • Logging improvements

[1.8.8] - 2019-08-06

Added

  • Config option for custom logging function

[1.8.7] - 2019-05-20

Changed

  • Use better temp directory for files

[1.8.6] - 2019-05-11

Fixes

  • Remove .git from published npm package

[1.8.5] - 2019-04-09

Changed

  • Prevent timeout on all queries

[1.8.4] - 2019-03-31

Added

  • Index on stop_id

Changed

  • Strip byte-order-markers if present when importing

[1.8.3] - 2019-03-26

Added

  • Support for GET headers

[1.8.2] - 2019-03-11

Changed

  • Renamed config variable to show_trip_continuation

[1.8.1] - 2019-02-28

Added

  • Changelog

Changed

  • Fixed issue with geojson consolidation

[1.8.0] - 2019-02-28

Changed

  • Updated all methods so that query objects remain unchanged
  • Updated dependencies

[1.0.0] - 2017-07-17

Breaking changes in version 1.0.0

As of version 1.0.0, all node-gtfs methods have changed to accept a query object instead of individual arguments. This allows for all fields of all GTFS files to be queried using this library. Most method names have been changed to be more general and more specific methods have been removed. For example, getRoutes now replaces getRoutesByAgency, getRoutesById, getRoutesByDistance and getRoutesByStop.

// Old method with individual arguments, no longer supported in `node-gtfs` 1.0.0
gtfs.getRoutesByStop(agency_key, stop_id)
.then(routes => {
  // do something with the array of `routes`
})

// Query in `node-gtfs` version 1.0.0
gtfs.getRoutes({
  stop_id: '123'
})
.then(routes => {
  // do something with the array of `routes`
})

[0.11.0] - 2017-07-04

As of version 0.11.0, node-gtfs methods don't support callbacks. Use promises instead:

gtfs.getAgencies()
.then(agencies => {
  // do something with the array of `agencies`
})
.catch(err => {
  // handle errors here
});

Or, you use async/await:

const myAwesomeFunction = async () => {
  try {
    const agencies = await gtfs.getAgencies();
  } catch (error) {
    // handle errors here
  }
}