Skip to content

Repository files navigation

➡️ 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';importpathfrom'node:path';constconfig=JSON.parse(awaitreadFile(path.join(import.meta.dirname,'config.json'),'utf8'));try{awaitimportGtfs(config);}catch(error){console.error(error);}

Example Applications

GTFS-to-HTMLGTFS-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-geojsonGTFS-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-ChartGTFS-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 ValidatorGTFS 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-TTSGTFS-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 WidgetTransit Departures Widget creates a realtime transit departures widget from GTFS and GTFS-Realtime data.
GTFS-to-BlocksGTFS-to-Blocks reads transit data from GTFS and exports all trip segments sorted by block_id and their departure times in CSV format.

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
optiontypedescription
agenciesarrayAn array of GTFS files to be imported, and which files to exclude.
csvOptionsobjectOptions passed to csv-parse for parsing GTFS CSV files. Optional.
dbdatabase instanceAn existing database instance to use instead of relying on node-gtfs to connect. Optional.
downloadTimeoutintegerThe number of milliseconds to wait before throwing an error when downloading GTFS. Optional.
exportPathstringA path to a directory to put exported GTFS files. Optional, defaults to gtfs-export/<agency_name>.
gtfsRealtimeExpirationSecondsintegerAmount of time in seconds to allow GTFS-Realtime data to be stored in database before allowing to be deleted. Optional, defaults to 0.
ignoreDuplicatesbooleanWhether or not to ignore unique constraints on ids when importing GTFS, such as trip_id, calendar_id. Optional, defaults to false.
ignoreErrorsbooleanWhether or not to ignore errors during the import process. If true, failed files will be skipped while the rest are processed. Optional, defaults to false.
includeImportReportbooleanWhether to return a report object from importGtfs() containing details about what was imported and any errors encountered. Optional, defaults to false.
sqlitePathstringA path to a SQLite database. Optional, defaults to using an in-memory database.
verbosebooleanWhether 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

optiontypedescription
urlstringThe URL to a zipped GTFS file. Required if path not present.
pathstringA path to a zipped GTFS file or a directory of unzipped .txt files. Required if url is not present.
headersobjectAn object of HTTP headers in key:value format to use when fetching GTFS from the url specified. Optional.
prefixstringA prefix to be added to every ID field maintain uniqueness when importing multiple GTFS from multiple agencies. Optional.
excludearrayAn array of GTFS file names (without .txt) to exclude when importing. Optional.
fillEmptyAgencyIdbooleanWhen true, fills empty agency_id on routes, fares, and other files for single-agency feeds. Useful for shared databases. Defaults to false. Optional.
agencyIdstringExplicit agency_id to use when fillEmptyAgencyId is true and agency.txt does not define one. Also backfills the agency_id on the agency row itself. If agency.txt already defines an agency_id, that value takes precedence. Optional.
realtimeAlertsobjectAn 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.
realtimeTripUpdatesobjectAn 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.
realtimeVehiclePositionsobjectAn 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 databaseimport{importGtfs}from'gtfs';importDatabasefrom'better-sqlite3';constdb=newDatabase('/path/to/database');importGtfs({agencies: [{path: '/path/to/the/unzipped/gtfs/',},],db: db,});
// Using `openDb` from node-gtfs to open databaseimport{importGtfs,openDb}from'gtfs';constdb=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, defaults to 30000 (30 seconds).

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

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": 3600
}

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} Controls error handling behavior during GTFS import. When true, the import process will continue even when encountering errors, logging them instead of stopping execution. Defaults to false.

When enabled, ignoreErrors will:

  • Continue processing other GTFS files when one file fails
  • Log error messages instead of throwing exceptions
  • Skip problematic records within files while importing valid ones
  • Handle various error types including:
    • Invalid CSV data or malformed records
    • JSON parsing errors (for GeoJSON files)
    • Database constraint violations
    • File read/write errors
    • GTFS-Realtime API failures

Use cases:

  • Importing from multiple GTFS sources where some may have data quality issues
  • Processing large datasets where minor errors shouldn't halt the entire import
  • Development/testing scenarios where you want to see all errors at once

⚠️ Important considerations:

  • Errors are logged but not thrown, so you may miss critical data issues
  • Partial imports may result in incomplete or inconsistent data
  • Consider using the exclude config option to skip problematic files entirely instead of ignoring errors
{
"agencies": [
{
"path": "/path/to/the/unzipped/gtfs/"
}
],
"ignoreErrors": true
}

includeImportReport

{Boolean} When true, importGtfs() returns an ImportReport object containing details about the import (record counts, errors encountered, etc.) instead of returning void. Useful when combined with ignoreErrors: true to inspect what failed after a partial import. Defaults to false.

import{importGtfs}from'gtfs';constreport=awaitimportGtfs({agencies: [{path: '/path/to/gtfs'}],ignoreErrors: true,includeImportReport: true,});console.log(report.errors);

sqlitePath

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

"sqlitePath": "/tmp/gtfs.sqlite"

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';constconfig={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 somewhereconsole.log(text);},};awaitimportGtfs(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';importpathfrom'node:path';constconfig=JSON.parse(awaitreadFile(path.join(import.meta.dirname,'config.json'),'utf8'));awaitimportGtfs(config);

Configuration can be a JSON object in your code

import{importGtfs}from'gtfs';constconfig={sqlitePath: '/tmp/gtfs.sqlite',agencies: [{url: 'https://www.bart.gov/dev/schedules/google_transit.zip',exclude: ['shapes'],},],};awaitimportGtfs(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';importpathfrom'node:path';constconfig=JSON.parse(awaitreadFile(path.join(import.meta.dirname,'config.json'),'utf8'));awaitupdateGtfsRealtime(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';constconfig={sqlitePath: '/tmp/gtfs.sqlite',agencies: [{url: 'https://www.bart.gov/dev/schedules/google_transit.zip',exclude: ['shapes'],},],};awaitexportGtfs(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';importpathfrom'node:path';constconfig=JSON.parse(awaitreadFile(path.join(import.meta.dirname,'config.json'),'utf8'));constdb=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';constdb=openDb(config);// Do some stuff here// Close database connection when done.closeDb(db);

Deleting a Database

You can use deleteDb to close and delete a database. For file-backed databases the file is removed from the filesystem. For in-memory databases (the default) the connection is closed and the internal reference is removed — no filesystem operation is performed.

import{deleteDb,openDb}from'gtfs';constdb=openDb(config);// Do some stuff here// Delete the databasedeleteDb(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';importpathfrom'node:path';constconfig=JSON.parse(awaitreadFile(path.join(import.meta.dirname,'config.json'),'utf8'));constdb=openDb(config);constroutes=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';importpathfrom'node:path';constconfig=JSON.parse(awaitreadFile(path.join(import.meta.dirname,'config.json'),'utf8'));constdb=openDb(config);consttrips=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';importpathfrom'node:path';constconfig=JSON.parse(awaitreadFile(path.join(import.meta.dirname,'config.json'),'utf8'));constdb=openDb(config);conststops=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 agenciesconstagencies=getAgencies();// Get a specific agencyconstagencies=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 areasconstareas=getAreas();// Get a specific areaconstareas=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 attributionsconstattributions=getAttributions();// Get a specific attributionconstattributions=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 rulesconstbookingRules=getBookingRules();// Get a specific booking ruleconstbookingRules=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_nameconstroutes=getRoutes({},[],[['route_short_name','ASC']]);// Get a specific routeconstroutes=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`. */constroutes=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 stopsconststops=getStops();// Get a specific stop by stop_idconststops=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`. */conststops=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`. */conststops=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`. */conststops=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. */conststops=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 geoJSONconststopsGeojson=getStopsAsGeoJSON();// Get all stops for a specific route as geoJSONconststopsGeojson=getStopsAsGeoJSON({route_id: 'Lo-16APR',});// Get all stops within a 1000m bounding box as geoJSONconststopsGeojson=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 stoptimesconststoptimes=getStoptimes();// Get all stoptimes for a specific stopconststoptimes=getStoptimes({stop_id: '70011',});// Get all stoptimes for a specific trip, sorted by stop_sequenceconststoptimes=getStoptimes({trip_id: '37a',},[],[['stop_sequence','ASC']],);// Get all stoptimes for a specific stop and service_idconststoptimes=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 service date. */conststoptimes=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. */conststoptimes=getStoptimes({stop_id: '70011',date: 20160704,start_time: '11:30:00',end_time: '11:45:00'});/* * ⚠️ By default, when using the `date` parameter in a query, it will NOT * include stoptimes for trips whose service date is the previous day but * whose stoptimes occur after midnight (i.e., times greater than 24:00:00 * in GTFS, such as 25:15:00 for 1:15 AM the next day). * * To retrieve all stoptimes for a calendar date including those from  * trips assigned to the previous service date but occurring after  * midnight: * 1. Call `getStoptimes` with the target date: * 2. Call `getStoptimes` with the previous date and `start_time: '24:00:00'`: * 3. Combine both results for a complete set of stoptimes for July 5th. * * This approach ensures you include: * - All stoptimes for trips whose service date is July 4th but whose  * stoptimes occur after midnight (i.e., in the early hours of July 5th) * - All stoptimes for trips whose service date is July 5th (which can  * include trips with stoptimes that occur on July 6th after midnight ) */conststoptimesToday=getStoptimes({date: 20240705});conststoptimesYesterdayAfterMidnight=getStoptimes({date: 20240704,start_time: '24:00:00'})constmergedStoptimes=[
...stoptimesToday,
...stoptimesYesterdayAfterMidnight];

getTrips(query, fields, sortBy, options)

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

import{getTrips}from'gtfs';// Get all tripsconsttrips=getTrips();// Get trips for a specific route and directionconsttrips=getTrips({route_id: 'Lo-16APR',direction_id: 0});// Get trips for direction '' or nullconsttrips=getTrips({route_id: 'Lo-16APR',direction_id: null});// Get trips for a specific route and direction limited by a service_idconsttrips=getTrips({route_id: 'Lo-16APR',direction_id: 0,service_id: 'CT-16APR-Caltrain-Weekday-01',});/* * `getTrips` allows passing a `date` in the query to return only trips  * for a specific service date. */consttrips=getTrips({route_id: 'Bu-16APR',date: 20170416});

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 agencyconstshapes=getShapes();/* * `getShapes` allows passing a `route_id` in the query and it will query * trips to find all shapes served by that `route_id`. */constshapes=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`. */constshapes=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`. */constshapes=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 agencyconstshapesGeojson=getShapesAsGeoJSON();// Get geoJSON of shapes for a specific routeconstshapesGeojson=getShapesAsGeoJSON({route_id: 'Lo-16APR',});// Get geoJSON of shapes for a specific tripconstshapesGeojson=getShapesAsGeoJSON({trip_id: '37a',});// Get geoJSON of shapes for a specific `service_id`constshapesGeojson=getShapesAsGeoJSON({service_id: 'CT-16APR-Caltrain-Sunday-02',});// Get geoJSON of shapes for a specific `shape_id`constshapesGeojson=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 agencyconstcalendars=getCalendars();// Get calendars for a specific `service_id`constcalendars=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 dateconstserviceIds=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 agencyconstcalendarDates=getCalendarDates();// Get calendar_dates for a specific `service_id`constcalendarDates=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 agencyconstfareAttributes=getFareAttributes();// Get `fare_attributes` for a specific `fare_id`constfareAttributes=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 rulesconstfareLegRules=getFareLegRules();// Get fare leg rules for a specific fare productconstfareLegRules=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 mediaconstgetFareMedia=getFareMedia();// Get a specific fare mediaconstfareMedia=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 productsconstfareProducts=getFareProducts();// Get a specific fare productconstfareProducts=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 agencyconstfareRules=getFareRules();// Get fare_rules for a specific routeconstfareRules=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 rulesconstfareTransferRules=getFareTransferRules();// Get a all fare transfer rules for a specific fare productconstfareTransferRules=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_infoconstfeedInfo=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 frequenciesconstfrequencies=getFrequencies();// Get frequencies for a specific tripconstfrequencies=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 levelsconstlevels=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 groupsconstlocationGroups=getLocationGroups();// Get a specific location groupconstlocationGroups=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 stopsconstlocationGroupStops=getLocationGroupStops();// Get location group stops for a specific stop_idconstlocationGroups=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 locationsconstlocations=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 pathwaysconstpathways=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 timeframesconsttimeframes=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 transfersconsttransfers=getTransfers();// Get transfers for a specific stopconsttransfers=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 translationsconsttranslations=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 areasconststopAreas=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 networksconstnetworks=getNetworks();// Get networks for a specific network_idconstnetworks=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_networksconstrouteNetworks=getRouteNetworks();// Get route_networks for a specific network_idconstrouteNetworks=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 agencyconsttimetables=getTimetables();// Get a specific timetableconsttimetables=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_ordersconsttimetableStopOrders=getTimetableStopOrders();// Get timetable_stop_orders for a specific timetableconsttimetableStopOrders=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 agencyconsttimetablePages=getTimetablePages();// Get a specific timetable_pageconsttimetablePages=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 agencyconsttimetableNotes=getTimetableNotes();// Get a specific timetable_noteconsttimetableNotes=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 agencyconsttimetableNotesReferences=getTimetableNotesReferences();// Get all timetable_notes_references for a specific timetableconsttimetableNotesReferences=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. Each alert includes a nested informed_entities array containing all related informed entities (stops, routes, trips) that the alert applies to. 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

Each alert has an informed_entities array containing all stops, routes, and trips the alert applies to. The active_period field is a JSON-serialised array of {start, end} Unix timestamp objects representing when the alert is active. The convenience fields start_time and end_time contain the start and end of the first active period (or null if none is set).

import{getServiceAlerts}from'gtfs';// Get all service alertsconstserviceAlerts=getServiceAlerts();// Get alerts affecting a specific stopconststopAlerts=getServiceAlerts({stop_id: 'STOP_ID'});// Get alerts affecting a specific routeconstrouteAlerts=getServiceAlerts({route_id: 'ROUTE_ID'});

getServiceAlertInformedEntities(query, fields, sortBy, options)

Returns an array of GTFS Realtime service alert informed entities that match query parameters. Each row represents a single entity (stop, route, trip, etc.) that a service alert applies to, linked back to its alert via alert_id. Use this for direct access to the service_alert_informed_entities table; use getServiceAlerts() to get alerts with all informed entities already nested.

More details on Service Alert Informed Entities

import{getServiceAlertInformedEntities}from'gtfs';// Get all service alert informed entitiesconstinformedEntities=getServiceAlertInformedEntities();// Get all informed entities for a specific alertconstinformedEntities=getServiceAlertInformedEntities({alert_id: 'some-alert-id'});

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 updatesconsttripUpdates=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 updatesconststopTimeUpdates=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 dataconstvehiclePositions=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 attributesconstcalendarAttributes=getCalendarAttributes();// Get calendar attributes for specific serviceconstcalendarAttributes=getCalendarAttributes({service_id: '1234',});

getDirections(query, fields, sortBy, options)

Returns an array of directions that match query parameters.

import{getDirections}from'gtfs';// Get all directionsconstdirections=getDirections();// Get directions for a specific routeconstdirections=getDirections({route_id: '1234',});// Get directions for a specific route and directionconstdirections=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 attributesconstrouteAttributes=getRouteAttributes();// Get route attributes for specific routeconstrouteAttributes=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 attributesconststopAttributes=getStopAttributes();// Get stop attributes for specific stopconststopAttributes=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_alightconstboardAlights=getBoardAlights();// Get board_alight for a specific tripconstboardAlights=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_infoconstrideFeedInfos=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_tripconstriderTrips=getRiderTrips();// Get rider_trip for a specific tripconstriderTrips=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 ridershipconstriderships=getRidership();// Get ridership for a specific routeconstriderships=getRidership({route_id: '123',});

getRiderCategories(query, fields, sortBy, options)

Returns an array of rider categories that match query parameters. Details on rider_categories.txt

import{getRiderCategories}from'gtfs';// Get all rider categoriesconstriderCategories=getRiderCategories();// Get a specific rider categoryconstriderCategories=getRiderCategories({rider_category_id: '1',});

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_capacityconsttripCapacities=getTripCapacities();// Get trip_capacity for a specific tripconsttripCapacities=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 deadheadsconstdeadheads=getDeadheads();// Get deadheads for a specific blockconstdeadheads=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_timesconstdeadheadTimes=getDeadheadTimes();// Get deadhead_times for a specific deadheadconstdeadheadTimes=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_locationsconstopsLocations=getOpsLocations();// Get a specific ops_locationsconstopsLocations=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_piecesconstrunsPieces=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_eventsconstrunEvents=getRunEvents();// Get run_events for a specific piececonstrunEvents=getRunEvents({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_journeyconsttripsDatedVehicleJourneys=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.constadvancedQueryOptions={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',},],};conststoptimes=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';constdb=openDb(config);// Get a specific tripconsttrip=db.prepare('SELECT * FROM trips WHERE trip_id = ?').get('123');// Get all stopsconststops=db.prepare('SELECT * from stops').all();// Get all calendar_ids for specific dateconstcalendarIds=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 tablesconststopIds=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 SQLconstsql="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

About

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

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Add copy buttons to all
 blocks
(function() {
function addCopyButtons() {
document.querySelectorAll('pre code').forEach(function(codeBlock) {
if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;
codeBlock.parentElement.setAttribute('data-copy-added', 'true');
var btn = document.createElement('button');
btn.textContent = 'Copy';
btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';
btn.onmouseover = function() { this.style.opacity = '1'; };
btn.onmouseout = function() { this.style.opacity = '0.7'; };
btn.onclick = function() {
navigator.clipboard.writeText(codeBlock.textContent).then(function() {
btn.textContent = 'Copied!';
setTimeout(function() { btn.textContent = 'Copy'; }, 1500);
});
};
codeBlock.parentElement.style.position = 'relative';
codeBlock.parentElement.appendChild(btn);
});
}
addCopyButtons();
// Re-run on dynamic content
var observer = new MutationObserver(addCopyButtons);
observer.observe(document.body, { childList: true, subtree: true });
})();
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
GitHub - LACMTA/node-gtfs: Import GTFS transit data into SQLite and query routes, stops, times, fares and more. · GitHub
Skip to content

Repository files navigation

➡️ 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';importpathfrom'node:path';constconfig=JSON.parse(awaitreadFile(path.join(import.meta.dirname,'config.json'),'utf8'));try{awaitimportGtfs(config);}catch(error){console.error(error);}

Example Applications

GTFS-to-HTMLGTFS-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-geojsonGTFS-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-ChartGTFS-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 ValidatorGTFS 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-TTSGTFS-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 WidgetTransit Departures Widget creates a realtime transit departures widget from GTFS and GTFS-Realtime data.
GTFS-to-BlocksGTFS-to-Blocks reads transit data from GTFS and exports all trip segments sorted by block_id and their departure times in CSV format.

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
optiontypedescription
agenciesarrayAn array of GTFS files to be imported, and which files to exclude.
csvOptionsobjectOptions passed to csv-parse for parsing GTFS CSV files. Optional.
dbdatabase instanceAn existing database instance to use instead of relying on node-gtfs to connect. Optional.
downloadTimeoutintegerThe number of milliseconds to wait before throwing an error when downloading GTFS. Optional.
exportPathstringA path to a directory to put exported GTFS files. Optional, defaults to gtfs-export/<agency_name>.
gtfsRealtimeExpirationSecondsintegerAmount of time in seconds to allow GTFS-Realtime data to be stored in database before allowing to be deleted. Optional, defaults to 0.
ignoreDuplicatesbooleanWhether or not to ignore unique constraints on ids when importing GTFS, such as trip_id, calendar_id. Optional, defaults to false.
ignoreErrorsbooleanWhether or not to ignore errors during the import process. If true, failed files will be skipped while the rest are processed. Optional, defaults to false.
includeImportReportbooleanWhether to return a report object from importGtfs() containing details about what was imported and any errors encountered. Optional, defaults to false.
sqlitePathstringA path to a SQLite database. Optional, defaults to using an in-memory database.
verbosebooleanWhether 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

optiontypedescription
urlstringThe URL to a zipped GTFS file. Required if path not present.
pathstringA path to a zipped GTFS file or a directory of unzipped .txt files. Required if url is not present.
headersobjectAn object of HTTP headers in key:value format to use when fetching GTFS from the url specified. Optional.
prefixstringA prefix to be added to every ID field maintain uniqueness when importing multiple GTFS from multiple agencies. Optional.
excludearrayAn array of GTFS file names (without .txt) to exclude when importing. Optional.
fillEmptyAgencyIdbooleanWhen true, fills empty agency_id on routes, fares, and other files for single-agency feeds. Useful for shared databases. Defaults to false. Optional.
agencyIdstringExplicit agency_id to use when fillEmptyAgencyId is true and agency.txt does not define one. Also backfills the agency_id on the agency row itself. If agency.txt already defines an agency_id, that value takes precedence. Optional.
realtimeAlertsobjectAn 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.
realtimeTripUpdatesobjectAn 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.
realtimeVehiclePositionsobjectAn 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 databaseimport{importGtfs}from'gtfs';importDatabasefrom'better-sqlite3';constdb=newDatabase('/path/to/database');importGtfs({agencies: [{path: '/path/to/the/unzipped/gtfs/',},],db: db,});
// Using `openDb` from node-gtfs to open databaseimport{importGtfs,openDb}from'gtfs';constdb=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, defaults to 30000 (30 seconds).

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

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": 3600
}

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} Controls error handling behavior during GTFS import. When true, the import process will continue even when encountering errors, logging them instead of stopping execution. Defaults to false.

When enabled, ignoreErrors will:

  • Continue processing other GTFS files when one file fails
  • Log error messages instead of throwing exceptions
  • Skip problematic records within files while importing valid ones
  • Handle various error types including:
    • Invalid CSV data or malformed records
    • JSON parsing errors (for GeoJSON files)
    • Database constraint violations
    • File read/write errors
    • GTFS-Realtime API failures

Use cases:

  • Importing from multiple GTFS sources where some may have data quality issues
  • Processing large datasets where minor errors shouldn't halt the entire import
  • Development/testing scenarios where you want to see all errors at once

⚠️ Important considerations:

  • Errors are logged but not thrown, so you may miss critical data issues
  • Partial imports may result in incomplete or inconsistent data
  • Consider using the exclude config option to skip problematic files entirely instead of ignoring errors
{
"agencies": [
{
"path": "/path/to/the/unzipped/gtfs/"
}
],
"ignoreErrors": true
}

includeImportReport

{Boolean} When true, importGtfs() returns an ImportReport object containing details about the import (record counts, errors encountered, etc.) instead of returning void. Useful when combined with ignoreErrors: true to inspect what failed after a partial import. Defaults to false.

import{importGtfs}from'gtfs';constreport=awaitimportGtfs({agencies: [{path: '/path/to/gtfs'}],ignoreErrors: true,includeImportReport: true,});console.log(report.errors);

sqlitePath

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

"sqlitePath": "/tmp/gtfs.sqlite"

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';constconfig={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 somewhereconsole.log(text);},};awaitimportGtfs(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';importpathfrom'node:path';constconfig=JSON.parse(awaitreadFile(path.join(import.meta.dirname,'config.json'),'utf8'));awaitimportGtfs(config);

Configuration can be a JSON object in your code

import{importGtfs}from'gtfs';constconfig={sqlitePath: '/tmp/gtfs.sqlite',agencies: [{url: 'https://www.bart.gov/dev/schedules/google_transit.zip',exclude: ['shapes'],},],};awaitimportGtfs(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';importpathfrom'node:path';constconfig=JSON.parse(awaitreadFile(path.join(import.meta.dirname,'config.json'),'utf8'));awaitupdateGtfsRealtime(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';constconfig={sqlitePath: '/tmp/gtfs.sqlite',agencies: [{url: 'https://www.bart.gov/dev/schedules/google_transit.zip',exclude: ['shapes'],},],};awaitexportGtfs(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';importpathfrom'node:path';constconfig=JSON.parse(awaitreadFile(path.join(import.meta.dirname,'config.json'),'utf8'));constdb=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';constdb=openDb(config);// Do some stuff here// Close database connection when done.closeDb(db);

Deleting a Database

You can use deleteDb to close and delete a database. For file-backed databases the file is removed from the filesystem. For in-memory databases (the default) the connection is closed and the internal reference is removed — no filesystem operation is performed.

import{deleteDb,openDb}from'gtfs';constdb=openDb(config);// Do some stuff here// Delete the databasedeleteDb(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';importpathfrom'node:path';constconfig=JSON.parse(awaitreadFile(path.join(import.meta.dirname,'config.json'),'utf8'));constdb=openDb(config);constroutes=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';importpathfrom'node:path';constconfig=JSON.parse(awaitreadFile(path.join(import.meta.dirname,'config.json'),'utf8'));constdb=openDb(config);consttrips=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';importpathfrom'node:path';constconfig=JSON.parse(awaitreadFile(path.join(import.meta.dirname,'config.json'),'utf8'));constdb=openDb(config);conststops=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 agenciesconstagencies=getAgencies();// Get a specific agencyconstagencies=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 areasconstareas=getAreas();// Get a specific areaconstareas=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 attributionsconstattributions=getAttributions();// Get a specific attributionconstattributions=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 rulesconstbookingRules=getBookingRules();// Get a specific booking ruleconstbookingRules=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_nameconstroutes=getRoutes({},[],[['route_short_name','ASC']]);// Get a specific routeconstroutes=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`. */constroutes=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 stopsconststops=getStops();// Get a specific stop by stop_idconststops=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`. */conststops=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`. */conststops=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`. */conststops=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. */conststops=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 geoJSONconststopsGeojson=getStopsAsGeoJSON();// Get all stops for a specific route as geoJSONconststopsGeojson=getStopsAsGeoJSON({route_id: 'Lo-16APR',});// Get all stops within a 1000m bounding box as geoJSONconststopsGeojson=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 stoptimesconststoptimes=getStoptimes();// Get all stoptimes for a specific stopconststoptimes=getStoptimes({stop_id: '70011',});// Get all stoptimes for a specific trip, sorted by stop_sequenceconststoptimes=getStoptimes({trip_id: '37a',},[],[['stop_sequence','ASC']],);// Get all stoptimes for a specific stop and service_idconststoptimes=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 service date. */conststoptimes=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. */conststoptimes=getStoptimes({stop_id: '70011',date: 20160704,start_time: '11:30:00',end_time: '11:45:00'});/* * ⚠️ By default, when using the `date` parameter in a query, it will NOT * include stoptimes for trips whose service date is the previous day but * whose stoptimes occur after midnight (i.e., times greater than 24:00:00 * in GTFS, such as 25:15:00 for 1:15 AM the next day). * * To retrieve all stoptimes for a calendar date including those from  * trips assigned to the previous service date but occurring after  * midnight: * 1. Call `getStoptimes` with the target date: * 2. Call `getStoptimes` with the previous date and `start_time: '24:00:00'`: * 3. Combine both results for a complete set of stoptimes for July 5th. * * This approach ensures you include: * - All stoptimes for trips whose service date is July 4th but whose  * stoptimes occur after midnight (i.e., in the early hours of July 5th) * - All stoptimes for trips whose service date is July 5th (which can  * include trips with stoptimes that occur on July 6th after midnight ) */conststoptimesToday=getStoptimes({date: 20240705});conststoptimesYesterdayAfterMidnight=getStoptimes({date: 20240704,start_time: '24:00:00'})constmergedStoptimes=[
...stoptimesToday,
...stoptimesYesterdayAfterMidnight];

getTrips(query, fields, sortBy, options)

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

import{getTrips}from'gtfs';// Get all tripsconsttrips=getTrips();// Get trips for a specific route and directionconsttrips=getTrips({route_id: 'Lo-16APR',direction_id: 0});// Get trips for direction '' or nullconsttrips=getTrips({route_id: 'Lo-16APR',direction_id: null});// Get trips for a specific route and direction limited by a service_idconsttrips=getTrips({route_id: 'Lo-16APR',direction_id: 0,service_id: 'CT-16APR-Caltrain-Weekday-01',});/* * `getTrips` allows passing a `date` in the query to return only trips  * for a specific service date. */consttrips=getTrips({route_id: 'Bu-16APR',date: 20170416});

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 agencyconstshapes=getShapes();/* * `getShapes` allows passing a `route_id` in the query and it will query * trips to find all shapes served by that `route_id`. */constshapes=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`. */constshapes=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`. */constshapes=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 agencyconstshapesGeojson=getShapesAsGeoJSON();// Get geoJSON of shapes for a specific routeconstshapesGeojson=getShapesAsGeoJSON({route_id: 'Lo-16APR',});// Get geoJSON of shapes for a specific tripconstshapesGeojson=getShapesAsGeoJSON({trip_id: '37a',});// Get geoJSON of shapes for a specific `service_id`constshapesGeojson=getShapesAsGeoJSON({service_id: 'CT-16APR-Caltrain-Sunday-02',});// Get geoJSON of shapes for a specific `shape_id`constshapesGeojson=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 agencyconstcalendars=getCalendars();// Get calendars for a specific `service_id`constcalendars=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 dateconstserviceIds=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 agencyconstcalendarDates=getCalendarDates();// Get calendar_dates for a specific `service_id`constcalendarDates=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 agencyconstfareAttributes=getFareAttributes();// Get `fare_attributes` for a specific `fare_id`constfareAttributes=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 rulesconstfareLegRules=getFareLegRules();// Get fare leg rules for a specific fare productconstfareLegRules=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 mediaconstgetFareMedia=getFareMedia();// Get a specific fare mediaconstfareMedia=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 productsconstfareProducts=getFareProducts();// Get a specific fare productconstfareProducts=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 agencyconstfareRules=getFareRules();// Get fare_rules for a specific routeconstfareRules=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 rulesconstfareTransferRules=getFareTransferRules();// Get a all fare transfer rules for a specific fare productconstfareTransferRules=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_infoconstfeedInfo=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 frequenciesconstfrequencies=getFrequencies();// Get frequencies for a specific tripconstfrequencies=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 levelsconstlevels=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 groupsconstlocationGroups=getLocationGroups();// Get a specific location groupconstlocationGroups=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 stopsconstlocationGroupStops=getLocationGroupStops();// Get location group stops for a specific stop_idconstlocationGroups=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 locationsconstlocations=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 pathwaysconstpathways=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 timeframesconsttimeframes=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 transfersconsttransfers=getTransfers();// Get transfers for a specific stopconsttransfers=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 translationsconsttranslations=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 areasconststopAreas=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 networksconstnetworks=getNetworks();// Get networks for a specific network_idconstnetworks=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_networksconstrouteNetworks=getRouteNetworks();// Get route_networks for a specific network_idconstrouteNetworks=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 agencyconsttimetables=getTimetables();// Get a specific timetableconsttimetables=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_ordersconsttimetableStopOrders=getTimetableStopOrders();// Get timetable_stop_orders for a specific timetableconsttimetableStopOrders=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 agencyconsttimetablePages=getTimetablePages();// Get a specific timetable_pageconsttimetablePages=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 agencyconsttimetableNotes=getTimetableNotes();// Get a specific timetable_noteconsttimetableNotes=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 agencyconsttimetableNotesReferences=getTimetableNotesReferences();// Get all timetable_notes_references for a specific timetableconsttimetableNotesReferences=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. Each alert includes a nested informed_entities array containing all related informed entities (stops, routes, trips) that the alert applies to. 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

Each alert has an informed_entities array containing all stops, routes, and trips the alert applies to. The active_period field is a JSON-serialised array of {start, end} Unix timestamp objects representing when the alert is active. The convenience fields start_time and end_time contain the start and end of the first active period (or null if none is set).

import{getServiceAlerts}from'gtfs';// Get all service alertsconstserviceAlerts=getServiceAlerts();// Get alerts affecting a specific stopconststopAlerts=getServiceAlerts({stop_id: 'STOP_ID'});// Get alerts affecting a specific routeconstrouteAlerts=getServiceAlerts({route_id: 'ROUTE_ID'});

getServiceAlertInformedEntities(query, fields, sortBy, options)

Returns an array of GTFS Realtime service alert informed entities that match query parameters. Each row represents a single entity (stop, route, trip, etc.) that a service alert applies to, linked back to its alert via alert_id. Use this for direct access to the service_alert_informed_entities table; use getServiceAlerts() to get alerts with all informed entities already nested.

More details on Service Alert Informed Entities

import{getServiceAlertInformedEntities}from'gtfs';// Get all service alert informed entitiesconstinformedEntities=getServiceAlertInformedEntities();// Get all informed entities for a specific alertconstinformedEntities=getServiceAlertInformedEntities({alert_id: 'some-alert-id'});

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 updatesconsttripUpdates=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 updatesconststopTimeUpdates=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 dataconstvehiclePositions=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 attributesconstcalendarAttributes=getCalendarAttributes();// Get calendar attributes for specific serviceconstcalendarAttributes=getCalendarAttributes({service_id: '1234',});

getDirections(query, fields, sortBy, options)

Returns an array of directions that match query parameters.

import{getDirections}from'gtfs';// Get all directionsconstdirections=getDirections();// Get directions for a specific routeconstdirections=getDirections({route_id: '1234',});// Get directions for a specific route and directionconstdirections=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 attributesconstrouteAttributes=getRouteAttributes();// Get route attributes for specific routeconstrouteAttributes=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 attributesconststopAttributes=getStopAttributes();// Get stop attributes for specific stopconststopAttributes=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_alightconstboardAlights=getBoardAlights();// Get board_alight for a specific tripconstboardAlights=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_infoconstrideFeedInfos=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_tripconstriderTrips=getRiderTrips();// Get rider_trip for a specific tripconstriderTrips=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 ridershipconstriderships=getRidership();// Get ridership for a specific routeconstriderships=getRidership({route_id: '123',});

getRiderCategories(query, fields, sortBy, options)

Returns an array of rider categories that match query parameters. Details on rider_categories.txt

import{getRiderCategories}from'gtfs';// Get all rider categoriesconstriderCategories=getRiderCategories();// Get a specific rider categoryconstriderCategories=getRiderCategories({rider_category_id: '1',});

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_capacityconsttripCapacities=getTripCapacities();// Get trip_capacity for a specific tripconsttripCapacities=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 deadheadsconstdeadheads=getDeadheads();// Get deadheads for a specific blockconstdeadheads=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_timesconstdeadheadTimes=getDeadheadTimes();// Get deadhead_times for a specific deadheadconstdeadheadTimes=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_locationsconstopsLocations=getOpsLocations();// Get a specific ops_locationsconstopsLocations=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_piecesconstrunsPieces=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_eventsconstrunEvents=getRunEvents();// Get run_events for a specific piececonstrunEvents=getRunEvents({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_journeyconsttripsDatedVehicleJourneys=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.constadvancedQueryOptions={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',},],};conststoptimes=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';constdb=openDb(config);// Get a specific tripconsttrip=db.prepare('SELECT * FROM trips WHERE trip_id = ?').get('123');// Get all stopsconststops=db.prepare('SELECT * from stops').all();// Get all calendar_ids for specific dateconstcalendarIds=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 tablesconststopIds=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 SQLconstsql="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

About

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

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Force GitHub README to respect dark mode (function() { var style = document.createElement('style'); style.textContent = ' .markdown-body { color-scheme: dark light; } .markdown-body pre { background: #161b22 !important; } .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; } .markdown-body table th, .markdown-body table td { border-color: #30363d !important; } .markdown-body img { background: #0d1117; } .markdown-body blockquote { border-left-color: #8b949e; } .markdown-body hr { border-color: #30363d; } '; document.head.appendChild(style); })(); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' GitHub - LACMTA/node-gtfs: Import GTFS transit data into SQLite and query routes, stops, times, fares and more. · GitHub
Skip to content

Repository files navigation

➡️ 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';importpathfrom'node:path';constconfig=JSON.parse(awaitreadFile(path.join(import.meta.dirname,'config.json'),'utf8'));try{awaitimportGtfs(config);}catch(error){console.error(error);}

Example Applications

GTFS-to-HTMLGTFS-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-geojsonGTFS-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-ChartGTFS-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 ValidatorGTFS 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-TTSGTFS-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 WidgetTransit Departures Widget creates a realtime transit departures widget from GTFS and GTFS-Realtime data.
GTFS-to-BlocksGTFS-to-Blocks reads transit data from GTFS and exports all trip segments sorted by block_id and their departure times in CSV format.

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
optiontypedescription
agenciesarrayAn array of GTFS files to be imported, and which files to exclude.
csvOptionsobjectOptions passed to csv-parse for parsing GTFS CSV files. Optional.
dbdatabase instanceAn existing database instance to use instead of relying on node-gtfs to connect. Optional.
downloadTimeoutintegerThe number of milliseconds to wait before throwing an error when downloading GTFS. Optional.
exportPathstringA path to a directory to put exported GTFS files. Optional, defaults to gtfs-export/<agency_name>.
gtfsRealtimeExpirationSecondsintegerAmount of time in seconds to allow GTFS-Realtime data to be stored in database before allowing to be deleted. Optional, defaults to 0.
ignoreDuplicatesbooleanWhether or not to ignore unique constraints on ids when importing GTFS, such as trip_id, calendar_id. Optional, defaults to false.
ignoreErrorsbooleanWhether or not to ignore errors during the import process. If true, failed files will be skipped while the rest are processed. Optional, defaults to false.
includeImportReportbooleanWhether to return a report object from importGtfs() containing details about what was imported and any errors encountered. Optional, defaults to false.
sqlitePathstringA path to a SQLite database. Optional, defaults to using an in-memory database.
verbosebooleanWhether 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

optiontypedescription
urlstringThe URL to a zipped GTFS file. Required if path not present.
pathstringA path to a zipped GTFS file or a directory of unzipped .txt files. Required if url is not present.
headersobjectAn object of HTTP headers in key:value format to use when fetching GTFS from the url specified. Optional.
prefixstringA prefix to be added to every ID field maintain uniqueness when importing multiple GTFS from multiple agencies. Optional.
excludearrayAn array of GTFS file names (without .txt) to exclude when importing. Optional.
fillEmptyAgencyIdbooleanWhen true, fills empty agency_id on routes, fares, and other files for single-agency feeds. Useful for shared databases. Defaults to false. Optional.
agencyIdstringExplicit agency_id to use when fillEmptyAgencyId is true and agency.txt does not define one. Also backfills the agency_id on the agency row itself. If agency.txt already defines an agency_id, that value takes precedence. Optional.
realtimeAlertsobjectAn 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.
realtimeTripUpdatesobjectAn 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.
realtimeVehiclePositionsobjectAn 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 databaseimport{importGtfs}from'gtfs';importDatabasefrom'better-sqlite3';constdb=newDatabase('/path/to/database');importGtfs({agencies: [{path: '/path/to/the/unzipped/gtfs/',},],db: db,});
// Using `openDb` from node-gtfs to open databaseimport{importGtfs,openDb}from'gtfs';constdb=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, defaults to 30000 (30 seconds).

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

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": 3600
}

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} Controls error handling behavior during GTFS import. When true, the import process will continue even when encountering errors, logging them instead of stopping execution. Defaults to false.

When enabled, ignoreErrors will:

  • Continue processing other GTFS files when one file fails
  • Log error messages instead of throwing exceptions
  • Skip problematic records within files while importing valid ones
  • Handle various error types including:
    • Invalid CSV data or malformed records
    • JSON parsing errors (for GeoJSON files)
    • Database constraint violations
    • File read/write errors
    • GTFS-Realtime API failures

Use cases:

  • Importing from multiple GTFS sources where some may have data quality issues
  • Processing large datasets where minor errors shouldn't halt the entire import
  • Development/testing scenarios where you want to see all errors at once

⚠️ Important considerations:

  • Errors are logged but not thrown, so you may miss critical data issues
  • Partial imports may result in incomplete or inconsistent data
  • Consider using the exclude config option to skip problematic files entirely instead of ignoring errors
{
"agencies": [
{
"path": "/path/to/the/unzipped/gtfs/"
}
],
"ignoreErrors": true
}

includeImportReport

{Boolean} When true, importGtfs() returns an ImportReport object containing details about the import (record counts, errors encountered, etc.) instead of returning void. Useful when combined with ignoreErrors: true to inspect what failed after a partial import. Defaults to false.

import{importGtfs}from'gtfs';constreport=awaitimportGtfs({agencies: [{path: '/path/to/gtfs'}],ignoreErrors: true,includeImportReport: true,});console.log(report.errors);

sqlitePath

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

"sqlitePath": "/tmp/gtfs.sqlite"

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';constconfig={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 somewhereconsole.log(text);},};awaitimportGtfs(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';importpathfrom'node:path';constconfig=JSON.parse(awaitreadFile(path.join(import.meta.dirname,'config.json'),'utf8'));awaitimportGtfs(config);

Configuration can be a JSON object in your code

import{importGtfs}from'gtfs';constconfig={sqlitePath: '/tmp/gtfs.sqlite',agencies: [{url: 'https://www.bart.gov/dev/schedules/google_transit.zip',exclude: ['shapes'],},],};awaitimportGtfs(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';importpathfrom'node:path';constconfig=JSON.parse(awaitreadFile(path.join(import.meta.dirname,'config.json'),'utf8'));awaitupdateGtfsRealtime(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';constconfig={sqlitePath: '/tmp/gtfs.sqlite',agencies: [{url: 'https://www.bart.gov/dev/schedules/google_transit.zip',exclude: ['shapes'],},],};awaitexportGtfs(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';importpathfrom'node:path';constconfig=JSON.parse(awaitreadFile(path.join(import.meta.dirname,'config.json'),'utf8'));constdb=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';constdb=openDb(config);// Do some stuff here// Close database connection when done.closeDb(db);

Deleting a Database

You can use deleteDb to close and delete a database. For file-backed databases the file is removed from the filesystem. For in-memory databases (the default) the connection is closed and the internal reference is removed — no filesystem operation is performed.

import{deleteDb,openDb}from'gtfs';constdb=openDb(config);// Do some stuff here// Delete the databasedeleteDb(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';importpathfrom'node:path';constconfig=JSON.parse(awaitreadFile(path.join(import.meta.dirname,'config.json'),'utf8'));constdb=openDb(config);constroutes=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';importpathfrom'node:path';constconfig=JSON.parse(awaitreadFile(path.join(import.meta.dirname,'config.json'),'utf8'));constdb=openDb(config);consttrips=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';importpathfrom'node:path';constconfig=JSON.parse(awaitreadFile(path.join(import.meta.dirname,'config.json'),'utf8'));constdb=openDb(config);conststops=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 agenciesconstagencies=getAgencies();// Get a specific agencyconstagencies=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 areasconstareas=getAreas();// Get a specific areaconstareas=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 attributionsconstattributions=getAttributions();// Get a specific attributionconstattributions=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 rulesconstbookingRules=getBookingRules();// Get a specific booking ruleconstbookingRules=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_nameconstroutes=getRoutes({},[],[['route_short_name','ASC']]);// Get a specific routeconstroutes=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`. */constroutes=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 stopsconststops=getStops();// Get a specific stop by stop_idconststops=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`. */conststops=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`. */conststops=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`. */conststops=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. */conststops=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 geoJSONconststopsGeojson=getStopsAsGeoJSON();// Get all stops for a specific route as geoJSONconststopsGeojson=getStopsAsGeoJSON({route_id: 'Lo-16APR',});// Get all stops within a 1000m bounding box as geoJSONconststopsGeojson=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 stoptimesconststoptimes=getStoptimes();// Get all stoptimes for a specific stopconststoptimes=getStoptimes({stop_id: '70011',});// Get all stoptimes for a specific trip, sorted by stop_sequenceconststoptimes=getStoptimes({trip_id: '37a',},[],[['stop_sequence','ASC']],);// Get all stoptimes for a specific stop and service_idconststoptimes=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 service date. */conststoptimes=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. */conststoptimes=getStoptimes({stop_id: '70011',date: 20160704,start_time: '11:30:00',end_time: '11:45:00'});/* * ⚠️ By default, when using the `date` parameter in a query, it will NOT * include stoptimes for trips whose service date is the previous day but * whose stoptimes occur after midnight (i.e., times greater than 24:00:00 * in GTFS, such as 25:15:00 for 1:15 AM the next day). * * To retrieve all stoptimes for a calendar date including those from  * trips assigned to the previous service date but occurring after  * midnight: * 1. Call `getStoptimes` with the target date: * 2. Call `getStoptimes` with the previous date and `start_time: '24:00:00'`: * 3. Combine both results for a complete set of stoptimes for July 5th. * * This approach ensures you include: * - All stoptimes for trips whose service date is July 4th but whose  * stoptimes occur after midnight (i.e., in the early hours of July 5th) * - All stoptimes for trips whose service date is July 5th (which can  * include trips with stoptimes that occur on July 6th after midnight ) */conststoptimesToday=getStoptimes({date: 20240705});conststoptimesYesterdayAfterMidnight=getStoptimes({date: 20240704,start_time: '24:00:00'})constmergedStoptimes=[
...stoptimesToday,
...stoptimesYesterdayAfterMidnight];

getTrips(query, fields, sortBy, options)

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

import{getTrips}from'gtfs';// Get all tripsconsttrips=getTrips();// Get trips for a specific route and directionconsttrips=getTrips({route_id: 'Lo-16APR',direction_id: 0});// Get trips for direction '' or nullconsttrips=getTrips({route_id: 'Lo-16APR',direction_id: null});// Get trips for a specific route and direction limited by a service_idconsttrips=getTrips({route_id: 'Lo-16APR',direction_id: 0,service_id: 'CT-16APR-Caltrain-Weekday-01',});/* * `getTrips` allows passing a `date` in the query to return only trips  * for a specific service date. */consttrips=getTrips({route_id: 'Bu-16APR',date: 20170416});

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 agencyconstshapes=getShapes();/* * `getShapes` allows passing a `route_id` in the query and it will query * trips to find all shapes served by that `route_id`. */constshapes=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`. */constshapes=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`. */constshapes=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 agencyconstshapesGeojson=getShapesAsGeoJSON();// Get geoJSON of shapes for a specific routeconstshapesGeojson=getShapesAsGeoJSON({route_id: 'Lo-16APR',});// Get geoJSON of shapes for a specific tripconstshapesGeojson=getShapesAsGeoJSON({trip_id: '37a',});// Get geoJSON of shapes for a specific `service_id`constshapesGeojson=getShapesAsGeoJSON({service_id: 'CT-16APR-Caltrain-Sunday-02',});// Get geoJSON of shapes for a specific `shape_id`constshapesGeojson=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 agencyconstcalendars=getCalendars();// Get calendars for a specific `service_id`constcalendars=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 dateconstserviceIds=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 agencyconstcalendarDates=getCalendarDates();// Get calendar_dates for a specific `service_id`constcalendarDates=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 agencyconstfareAttributes=getFareAttributes();// Get `fare_attributes` for a specific `fare_id`constfareAttributes=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 rulesconstfareLegRules=getFareLegRules();// Get fare leg rules for a specific fare productconstfareLegRules=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 mediaconstgetFareMedia=getFareMedia();// Get a specific fare mediaconstfareMedia=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 productsconstfareProducts=getFareProducts();// Get a specific fare productconstfareProducts=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 agencyconstfareRules=getFareRules();// Get fare_rules for a specific routeconstfareRules=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 rulesconstfareTransferRules=getFareTransferRules();// Get a all fare transfer rules for a specific fare productconstfareTransferRules=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_infoconstfeedInfo=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 frequenciesconstfrequencies=getFrequencies();// Get frequencies for a specific tripconstfrequencies=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 levelsconstlevels=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 groupsconstlocationGroups=getLocationGroups();// Get a specific location groupconstlocationGroups=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 stopsconstlocationGroupStops=getLocationGroupStops();// Get location group stops for a specific stop_idconstlocationGroups=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 locationsconstlocations=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 pathwaysconstpathways=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 timeframesconsttimeframes=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 transfersconsttransfers=getTransfers();// Get transfers for a specific stopconsttransfers=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 translationsconsttranslations=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 areasconststopAreas=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 networksconstnetworks=getNetworks();// Get networks for a specific network_idconstnetworks=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_networksconstrouteNetworks=getRouteNetworks();// Get route_networks for a specific network_idconstrouteNetworks=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 agencyconsttimetables=getTimetables();// Get a specific timetableconsttimetables=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_ordersconsttimetableStopOrders=getTimetableStopOrders();// Get timetable_stop_orders for a specific timetableconsttimetableStopOrders=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 agencyconsttimetablePages=getTimetablePages();// Get a specific timetable_pageconsttimetablePages=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 agencyconsttimetableNotes=getTimetableNotes();// Get a specific timetable_noteconsttimetableNotes=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 agencyconsttimetableNotesReferences=getTimetableNotesReferences();// Get all timetable_notes_references for a specific timetableconsttimetableNotesReferences=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. Each alert includes a nested informed_entities array containing all related informed entities (stops, routes, trips) that the alert applies to. 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

Each alert has an informed_entities array containing all stops, routes, and trips the alert applies to. The active_period field is a JSON-serialised array of {start, end} Unix timestamp objects representing when the alert is active. The convenience fields start_time and end_time contain the start and end of the first active period (or null if none is set).

import{getServiceAlerts}from'gtfs';// Get all service alertsconstserviceAlerts=getServiceAlerts();// Get alerts affecting a specific stopconststopAlerts=getServiceAlerts({stop_id: 'STOP_ID'});// Get alerts affecting a specific routeconstrouteAlerts=getServiceAlerts({route_id: 'ROUTE_ID'});

getServiceAlertInformedEntities(query, fields, sortBy, options)

Returns an array of GTFS Realtime service alert informed entities that match query parameters. Each row represents a single entity (stop, route, trip, etc.) that a service alert applies to, linked back to its alert via alert_id. Use this for direct access to the service_alert_informed_entities table; use getServiceAlerts() to get alerts with all informed entities already nested.

More details on Service Alert Informed Entities

import{getServiceAlertInformedEntities}from'gtfs';// Get all service alert informed entitiesconstinformedEntities=getServiceAlertInformedEntities();// Get all informed entities for a specific alertconstinformedEntities=getServiceAlertInformedEntities({alert_id: 'some-alert-id'});

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 updatesconsttripUpdates=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 updatesconststopTimeUpdates=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 dataconstvehiclePositions=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 attributesconstcalendarAttributes=getCalendarAttributes();// Get calendar attributes for specific serviceconstcalendarAttributes=getCalendarAttributes({service_id: '1234',});

getDirections(query, fields, sortBy, options)

Returns an array of directions that match query parameters.

import{getDirections}from'gtfs';// Get all directionsconstdirections=getDirections();// Get directions for a specific routeconstdirections=getDirections({route_id: '1234',});// Get directions for a specific route and directionconstdirections=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 attributesconstrouteAttributes=getRouteAttributes();// Get route attributes for specific routeconstrouteAttributes=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 attributesconststopAttributes=getStopAttributes();// Get stop attributes for specific stopconststopAttributes=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_alightconstboardAlights=getBoardAlights();// Get board_alight for a specific tripconstboardAlights=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_infoconstrideFeedInfos=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_tripconstriderTrips=getRiderTrips();// Get rider_trip for a specific tripconstriderTrips=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 ridershipconstriderships=getRidership();// Get ridership for a specific routeconstriderships=getRidership({route_id: '123',});

getRiderCategories(query, fields, sortBy, options)

Returns an array of rider categories that match query parameters. Details on rider_categories.txt

import{getRiderCategories}from'gtfs';// Get all rider categoriesconstriderCategories=getRiderCategories();// Get a specific rider categoryconstriderCategories=getRiderCategories({rider_category_id: '1',});

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_capacityconsttripCapacities=getTripCapacities();// Get trip_capacity for a specific tripconsttripCapacities=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 deadheadsconstdeadheads=getDeadheads();// Get deadheads for a specific blockconstdeadheads=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_timesconstdeadheadTimes=getDeadheadTimes();// Get deadhead_times for a specific deadheadconstdeadheadTimes=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_locationsconstopsLocations=getOpsLocations();// Get a specific ops_locationsconstopsLocations=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_piecesconstrunsPieces=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_eventsconstrunEvents=getRunEvents();// Get run_events for a specific piececonstrunEvents=getRunEvents({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_journeyconsttripsDatedVehicleJourneys=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.constadvancedQueryOptions={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',},],};conststoptimes=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';constdb=openDb(config);// Get a specific tripconsttrip=db.prepare('SELECT * FROM trips WHERE trip_id = ?').get('123');// Get all stopsconststops=db.prepare('SELECT * from stops').all();// Get all calendar_ids for specific dateconstcalendarIds=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 tablesconststopIds=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 SQLconstsql="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

About

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

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Highlight search terms from Google/DuckDuckGo/Bing referrer (function() { var ref = document.referrer; var terms = []; if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) { var url = new URL(ref); var q = url.searchParams.get('q') || url.searchParams.get('p'); if (q) { terms = q.split(/\s+/).filter(function(t) { return t.length > 2; }); } } if (terms.length === 0) return; var style = document.createElement('style'); style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }'; document.head.appendChild(style); function highlight(node) { if (node.nodeType === 3) { // text node var text = node.textContent; var found = false; terms.forEach(function(term) { var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\]\\]/g, '\\') + ')', 'gi'); if (regex.test(text)) { found = true; var frag = document.createDocumentFragment(); var parts = text.split(regex); parts.forEach(function(part, i) { if (i % 2 === 0) { frag.appendChild(document.createTextNode(part)); } else { var span = document.createElement('span'); span.className = 'userscript-highlight'; span.textContent = part; frag.appendChild(span); } }); node.parentNode.replaceChild(frag, node); } }); } else if (node.nodeType === 1 && node.childNodes) { // element var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT']; if (!skipTags.includes(node.tagName)) { Array.from(node.childNodes).forEach(highlight); } } } highlight(document.body); // Re-highlight on dynamic content var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1 || node.nodeType === 3) highlight(node); }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' GitHub - LACMTA/node-gtfs: Import GTFS transit data into SQLite and query routes, stops, times, fares and more. · GitHub
Skip to content

Repository files navigation

➡️ 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';importpathfrom'node:path';constconfig=JSON.parse(awaitreadFile(path.join(import.meta.dirname,'config.json'),'utf8'));try{awaitimportGtfs(config);}catch(error){console.error(error);}

Example Applications

GTFS-to-HTMLGTFS-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-geojsonGTFS-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-ChartGTFS-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 ValidatorGTFS 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-TTSGTFS-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 WidgetTransit Departures Widget creates a realtime transit departures widget from GTFS and GTFS-Realtime data.
GTFS-to-BlocksGTFS-to-Blocks reads transit data from GTFS and exports all trip segments sorted by block_id and their departure times in CSV format.

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
optiontypedescription
agenciesarrayAn array of GTFS files to be imported, and which files to exclude.
csvOptionsobjectOptions passed to csv-parse for parsing GTFS CSV files. Optional.
dbdatabase instanceAn existing database instance to use instead of relying on node-gtfs to connect. Optional.
downloadTimeoutintegerThe number of milliseconds to wait before throwing an error when downloading GTFS. Optional.
exportPathstringA path to a directory to put exported GTFS files. Optional, defaults to gtfs-export/<agency_name>.
gtfsRealtimeExpirationSecondsintegerAmount of time in seconds to allow GTFS-Realtime data to be stored in database before allowing to be deleted. Optional, defaults to 0.
ignoreDuplicatesbooleanWhether or not to ignore unique constraints on ids when importing GTFS, such as trip_id, calendar_id. Optional, defaults to false.
ignoreErrorsbooleanWhether or not to ignore errors during the import process. If true, failed files will be skipped while the rest are processed. Optional, defaults to false.
includeImportReportbooleanWhether to return a report object from importGtfs() containing details about what was imported and any errors encountered. Optional, defaults to false.
sqlitePathstringA path to a SQLite database. Optional, defaults to using an in-memory database.
verbosebooleanWhether 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

optiontypedescription
urlstringThe URL to a zipped GTFS file. Required if path not present.
pathstringA path to a zipped GTFS file or a directory of unzipped .txt files. Required if url is not present.
headersobjectAn object of HTTP headers in key:value format to use when fetching GTFS from the url specified. Optional.
prefixstringA prefix to be added to every ID field maintain uniqueness when importing multiple GTFS from multiple agencies. Optional.
excludearrayAn array of GTFS file names (without .txt) to exclude when importing. Optional.
fillEmptyAgencyIdbooleanWhen true, fills empty agency_id on routes, fares, and other files for single-agency feeds. Useful for shared databases. Defaults to false. Optional.
agencyIdstringExplicit agency_id to use when fillEmptyAgencyId is true and agency.txt does not define one. Also backfills the agency_id on the agency row itself. If agency.txt already defines an agency_id, that value takes precedence. Optional.
realtimeAlertsobjectAn 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.
realtimeTripUpdatesobjectAn 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.
realtimeVehiclePositionsobjectAn 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 databaseimport{importGtfs}from'gtfs';importDatabasefrom'better-sqlite3';constdb=newDatabase('/path/to/database');importGtfs({agencies: [{path: '/path/to/the/unzipped/gtfs/',},],db: db,});
// Using `openDb` from node-gtfs to open databaseimport{importGtfs,openDb}from'gtfs';constdb=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, defaults to 30000 (30 seconds).

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

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": 3600
}

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} Controls error handling behavior during GTFS import. When true, the import process will continue even when encountering errors, logging them instead of stopping execution. Defaults to false.

When enabled, ignoreErrors will:

  • Continue processing other GTFS files when one file fails
  • Log error messages instead of throwing exceptions
  • Skip problematic records within files while importing valid ones
  • Handle various error types including:
    • Invalid CSV data or malformed records
    • JSON parsing errors (for GeoJSON files)
    • Database constraint violations
    • File read/write errors
    • GTFS-Realtime API failures

Use cases:

  • Importing from multiple GTFS sources where some may have data quality issues
  • Processing large datasets where minor errors shouldn't halt the entire import
  • Development/testing scenarios where you want to see all errors at once

⚠️ Important considerations:

  • Errors are logged but not thrown, so you may miss critical data issues
  • Partial imports may result in incomplete or inconsistent data
  • Consider using the exclude config option to skip problematic files entirely instead of ignoring errors
{
"agencies": [
{
"path": "/path/to/the/unzipped/gtfs/"
}
],
"ignoreErrors": true
}

includeImportReport

{Boolean} When true, importGtfs() returns an ImportReport object containing details about the import (record counts, errors encountered, etc.) instead of returning void. Useful when combined with ignoreErrors: true to inspect what failed after a partial import. Defaults to false.

import{importGtfs}from'gtfs';constreport=awaitimportGtfs({agencies: [{path: '/path/to/gtfs'}],ignoreErrors: true,includeImportReport: true,});console.log(report.errors);

sqlitePath

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

"sqlitePath": "/tmp/gtfs.sqlite"

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';constconfig={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 somewhereconsole.log(text);},};awaitimportGtfs(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';importpathfrom'node:path';constconfig=JSON.parse(awaitreadFile(path.join(import.meta.dirname,'config.json'),'utf8'));awaitimportGtfs(config);

Configuration can be a JSON object in your code

import{importGtfs}from'gtfs';constconfig={sqlitePath: '/tmp/gtfs.sqlite',agencies: [{url: 'https://www.bart.gov/dev/schedules/google_transit.zip',exclude: ['shapes'],},],};awaitimportGtfs(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';importpathfrom'node:path';constconfig=JSON.parse(awaitreadFile(path.join(import.meta.dirname,'config.json'),'utf8'));awaitupdateGtfsRealtime(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';constconfig={sqlitePath: '/tmp/gtfs.sqlite',agencies: [{url: 'https://www.bart.gov/dev/schedules/google_transit.zip',exclude: ['shapes'],},],};awaitexportGtfs(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';importpathfrom'node:path';constconfig=JSON.parse(awaitreadFile(path.join(import.meta.dirname,'config.json'),'utf8'));constdb=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';constdb=openDb(config);// Do some stuff here// Close database connection when done.closeDb(db);

Deleting a Database

You can use deleteDb to close and delete a database. For file-backed databases the file is removed from the filesystem. For in-memory databases (the default) the connection is closed and the internal reference is removed — no filesystem operation is performed.

import{deleteDb,openDb}from'gtfs';constdb=openDb(config);// Do some stuff here// Delete the databasedeleteDb(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';importpathfrom'node:path';constconfig=JSON.parse(awaitreadFile(path.join(import.meta.dirname,'config.json'),'utf8'));constdb=openDb(config);constroutes=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';importpathfrom'node:path';constconfig=JSON.parse(awaitreadFile(path.join(import.meta.dirname,'config.json'),'utf8'));constdb=openDb(config);consttrips=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';importpathfrom'node:path';constconfig=JSON.parse(awaitreadFile(path.join(import.meta.dirname,'config.json'),'utf8'));constdb=openDb(config);conststops=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 agenciesconstagencies=getAgencies();// Get a specific agencyconstagencies=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 areasconstareas=getAreas();// Get a specific areaconstareas=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 attributionsconstattributions=getAttributions();// Get a specific attributionconstattributions=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 rulesconstbookingRules=getBookingRules();// Get a specific booking ruleconstbookingRules=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_nameconstroutes=getRoutes({},[],[['route_short_name','ASC']]);// Get a specific routeconstroutes=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`. */constroutes=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 stopsconststops=getStops();// Get a specific stop by stop_idconststops=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`. */conststops=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`. */conststops=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`. */conststops=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. */conststops=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 geoJSONconststopsGeojson=getStopsAsGeoJSON();// Get all stops for a specific route as geoJSONconststopsGeojson=getStopsAsGeoJSON({route_id: 'Lo-16APR',});// Get all stops within a 1000m bounding box as geoJSONconststopsGeojson=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 stoptimesconststoptimes=getStoptimes();// Get all stoptimes for a specific stopconststoptimes=getStoptimes({stop_id: '70011',});// Get all stoptimes for a specific trip, sorted by stop_sequenceconststoptimes=getStoptimes({trip_id: '37a',},[],[['stop_sequence','ASC']],);// Get all stoptimes for a specific stop and service_idconststoptimes=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 service date. */conststoptimes=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. */conststoptimes=getStoptimes({stop_id: '70011',date: 20160704,start_time: '11:30:00',end_time: '11:45:00'});/* * ⚠️ By default, when using the `date` parameter in a query, it will NOT * include stoptimes for trips whose service date is the previous day but * whose stoptimes occur after midnight (i.e., times greater than 24:00:00 * in GTFS, such as 25:15:00 for 1:15 AM the next day). * * To retrieve all stoptimes for a calendar date including those from  * trips assigned to the previous service date but occurring after  * midnight: * 1. Call `getStoptimes` with the target date: * 2. Call `getStoptimes` with the previous date and `start_time: '24:00:00'`: * 3. Combine both results for a complete set of stoptimes for July 5th. * * This approach ensures you include: * - All stoptimes for trips whose service date is July 4th but whose  * stoptimes occur after midnight (i.e., in the early hours of July 5th) * - All stoptimes for trips whose service date is July 5th (which can  * include trips with stoptimes that occur on July 6th after midnight ) */conststoptimesToday=getStoptimes({date: 20240705});conststoptimesYesterdayAfterMidnight=getStoptimes({date: 20240704,start_time: '24:00:00'})constmergedStoptimes=[
...stoptimesToday,
...stoptimesYesterdayAfterMidnight];

getTrips(query, fields, sortBy, options)

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

import{getTrips}from'gtfs';// Get all tripsconsttrips=getTrips();// Get trips for a specific route and directionconsttrips=getTrips({route_id: 'Lo-16APR',direction_id: 0});// Get trips for direction '' or nullconsttrips=getTrips({route_id: 'Lo-16APR',direction_id: null});// Get trips for a specific route and direction limited by a service_idconsttrips=getTrips({route_id: 'Lo-16APR',direction_id: 0,service_id: 'CT-16APR-Caltrain-Weekday-01',});/* * `getTrips` allows passing a `date` in the query to return only trips  * for a specific service date. */consttrips=getTrips({route_id: 'Bu-16APR',date: 20170416});

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 agencyconstshapes=getShapes();/* * `getShapes` allows passing a `route_id` in the query and it will query * trips to find all shapes served by that `route_id`. */constshapes=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`. */constshapes=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`. */constshapes=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 agencyconstshapesGeojson=getShapesAsGeoJSON();// Get geoJSON of shapes for a specific routeconstshapesGeojson=getShapesAsGeoJSON({route_id: 'Lo-16APR',});// Get geoJSON of shapes for a specific tripconstshapesGeojson=getShapesAsGeoJSON({trip_id: '37a',});// Get geoJSON of shapes for a specific `service_id`constshapesGeojson=getShapesAsGeoJSON({service_id: 'CT-16APR-Caltrain-Sunday-02',});// Get geoJSON of shapes for a specific `shape_id`constshapesGeojson=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 agencyconstcalendars=getCalendars();// Get calendars for a specific `service_id`constcalendars=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 dateconstserviceIds=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 agencyconstcalendarDates=getCalendarDates();// Get calendar_dates for a specific `service_id`constcalendarDates=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 agencyconstfareAttributes=getFareAttributes();// Get `fare_attributes` for a specific `fare_id`constfareAttributes=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 rulesconstfareLegRules=getFareLegRules();// Get fare leg rules for a specific fare productconstfareLegRules=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 mediaconstgetFareMedia=getFareMedia();// Get a specific fare mediaconstfareMedia=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 productsconstfareProducts=getFareProducts();// Get a specific fare productconstfareProducts=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 agencyconstfareRules=getFareRules();// Get fare_rules for a specific routeconstfareRules=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 rulesconstfareTransferRules=getFareTransferRules();// Get a all fare transfer rules for a specific fare productconstfareTransferRules=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_infoconstfeedInfo=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 frequenciesconstfrequencies=getFrequencies();// Get frequencies for a specific tripconstfrequencies=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 levelsconstlevels=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 groupsconstlocationGroups=getLocationGroups();// Get a specific location groupconstlocationGroups=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 stopsconstlocationGroupStops=getLocationGroupStops();// Get location group stops for a specific stop_idconstlocationGroups=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 locationsconstlocations=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 pathwaysconstpathways=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 timeframesconsttimeframes=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 transfersconsttransfers=getTransfers();// Get transfers for a specific stopconsttransfers=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 translationsconsttranslations=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 areasconststopAreas=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 networksconstnetworks=getNetworks();// Get networks for a specific network_idconstnetworks=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_networksconstrouteNetworks=getRouteNetworks();// Get route_networks for a specific network_idconstrouteNetworks=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 agencyconsttimetables=getTimetables();// Get a specific timetableconsttimetables=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_ordersconsttimetableStopOrders=getTimetableStopOrders();// Get timetable_stop_orders for a specific timetableconsttimetableStopOrders=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 agencyconsttimetablePages=getTimetablePages();// Get a specific timetable_pageconsttimetablePages=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 agencyconsttimetableNotes=getTimetableNotes();// Get a specific timetable_noteconsttimetableNotes=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 agencyconsttimetableNotesReferences=getTimetableNotesReferences();// Get all timetable_notes_references for a specific timetableconsttimetableNotesReferences=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. Each alert includes a nested informed_entities array containing all related informed entities (stops, routes, trips) that the alert applies to. 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

Each alert has an informed_entities array containing all stops, routes, and trips the alert applies to. The active_period field is a JSON-serialised array of {start, end} Unix timestamp objects representing when the alert is active. The convenience fields start_time and end_time contain the start and end of the first active period (or null if none is set).

import{getServiceAlerts}from'gtfs';// Get all service alertsconstserviceAlerts=getServiceAlerts();// Get alerts affecting a specific stopconststopAlerts=getServiceAlerts({stop_id: 'STOP_ID'});// Get alerts affecting a specific routeconstrouteAlerts=getServiceAlerts({route_id: 'ROUTE_ID'});

getServiceAlertInformedEntities(query, fields, sortBy, options)

Returns an array of GTFS Realtime service alert informed entities that match query parameters. Each row represents a single entity (stop, route, trip, etc.) that a service alert applies to, linked back to its alert via alert_id. Use this for direct access to the service_alert_informed_entities table; use getServiceAlerts() to get alerts with all informed entities already nested.

More details on Service Alert Informed Entities

import{getServiceAlertInformedEntities}from'gtfs';// Get all service alert informed entitiesconstinformedEntities=getServiceAlertInformedEntities();// Get all informed entities for a specific alertconstinformedEntities=getServiceAlertInformedEntities({alert_id: 'some-alert-id'});

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 updatesconsttripUpdates=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 updatesconststopTimeUpdates=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 dataconstvehiclePositions=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 attributesconstcalendarAttributes=getCalendarAttributes();// Get calendar attributes for specific serviceconstcalendarAttributes=getCalendarAttributes({service_id: '1234',});

getDirections(query, fields, sortBy, options)

Returns an array of directions that match query parameters.

import{getDirections}from'gtfs';// Get all directionsconstdirections=getDirections();// Get directions for a specific routeconstdirections=getDirections({route_id: '1234',});// Get directions for a specific route and directionconstdirections=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 attributesconstrouteAttributes=getRouteAttributes();// Get route attributes for specific routeconstrouteAttributes=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 attributesconststopAttributes=getStopAttributes();// Get stop attributes for specific stopconststopAttributes=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_alightconstboardAlights=getBoardAlights();// Get board_alight for a specific tripconstboardAlights=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_infoconstrideFeedInfos=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_tripconstriderTrips=getRiderTrips();// Get rider_trip for a specific tripconstriderTrips=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 ridershipconstriderships=getRidership();// Get ridership for a specific routeconstriderships=getRidership({route_id: '123',});

getRiderCategories(query, fields, sortBy, options)

Returns an array of rider categories that match query parameters. Details on rider_categories.txt

import{getRiderCategories}from'gtfs';// Get all rider categoriesconstriderCategories=getRiderCategories();// Get a specific rider categoryconstriderCategories=getRiderCategories({rider_category_id: '1',});

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_capacityconsttripCapacities=getTripCapacities();// Get trip_capacity for a specific tripconsttripCapacities=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 deadheadsconstdeadheads=getDeadheads();// Get deadheads for a specific blockconstdeadheads=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_timesconstdeadheadTimes=getDeadheadTimes();// Get deadhead_times for a specific deadheadconstdeadheadTimes=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_locationsconstopsLocations=getOpsLocations();// Get a specific ops_locationsconstopsLocations=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_piecesconstrunsPieces=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_eventsconstrunEvents=getRunEvents();// Get run_events for a specific piececonstrunEvents=getRunEvents({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_journeyconsttripsDatedVehicleJourneys=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.constadvancedQueryOptions={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',},],};conststoptimes=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';constdb=openDb(config);// Get a specific tripconsttrip=db.prepare('SELECT * FROM trips WHERE trip_id = ?').get('123');// Get all stopsconststops=db.prepare('SELECT * from stops').all();// Get all calendar_ids for specific dateconstcalendarIds=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 tablesconststopIds=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 SQLconstsql="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

About

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

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Strip utm_, fbclid, gclid, etc. from all links on page (function() { var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid', 'ref', 'ref_src', 'source', 'medium', 'campaign']; function cleanUrl(url) { try { var u = new URL(url, window.location.origin); var changed = false; trackingParams.forEach(function(p) { if (u.searchParams.has(p)) { u.searchParams.delete(p); changed = true; } }); return changed ? u.toString() : url; } catch (e) { return url; } } function cleanLinks() { document.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } cleanLinks(); var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1) { if (node.tagName === 'A') cleanLinks(); node.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + ' GitHub - LACMTA/node-gtfs: Import GTFS transit data into SQLite and query routes, stops, times, fares and more. · GitHub
Skip to content

Repository files navigation

➡️ 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';importpathfrom'node:path';constconfig=JSON.parse(awaitreadFile(path.join(import.meta.dirname,'config.json'),'utf8'));try{awaitimportGtfs(config);}catch(error){console.error(error);}

Example Applications

GTFS-to-HTMLGTFS-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-geojsonGTFS-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-ChartGTFS-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 ValidatorGTFS 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-TTSGTFS-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 WidgetTransit Departures Widget creates a realtime transit departures widget from GTFS and GTFS-Realtime data.
GTFS-to-BlocksGTFS-to-Blocks reads transit data from GTFS and exports all trip segments sorted by block_id and their departure times in CSV format.

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
optiontypedescription
agenciesarrayAn array of GTFS files to be imported, and which files to exclude.
csvOptionsobjectOptions passed to csv-parse for parsing GTFS CSV files. Optional.
dbdatabase instanceAn existing database instance to use instead of relying on node-gtfs to connect. Optional.
downloadTimeoutintegerThe number of milliseconds to wait before throwing an error when downloading GTFS. Optional.
exportPathstringA path to a directory to put exported GTFS files. Optional, defaults to gtfs-export/<agency_name>.
gtfsRealtimeExpirationSecondsintegerAmount of time in seconds to allow GTFS-Realtime data to be stored in database before allowing to be deleted. Optional, defaults to 0.
ignoreDuplicatesbooleanWhether or not to ignore unique constraints on ids when importing GTFS, such as trip_id, calendar_id. Optional, defaults to false.
ignoreErrorsbooleanWhether or not to ignore errors during the import process. If true, failed files will be skipped while the rest are processed. Optional, defaults to false.
includeImportReportbooleanWhether to return a report object from importGtfs() containing details about what was imported and any errors encountered. Optional, defaults to false.
sqlitePathstringA path to a SQLite database. Optional, defaults to using an in-memory database.
verbosebooleanWhether 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

optiontypedescription
urlstringThe URL to a zipped GTFS file. Required if path not present.
pathstringA path to a zipped GTFS file or a directory of unzipped .txt files. Required if url is not present.
headersobjectAn object of HTTP headers in key:value format to use when fetching GTFS from the url specified. Optional.
prefixstringA prefix to be added to every ID field maintain uniqueness when importing multiple GTFS from multiple agencies. Optional.
excludearrayAn array of GTFS file names (without .txt) to exclude when importing. Optional.
fillEmptyAgencyIdbooleanWhen true, fills empty agency_id on routes, fares, and other files for single-agency feeds. Useful for shared databases. Defaults to false. Optional.
agencyIdstringExplicit agency_id to use when fillEmptyAgencyId is true and agency.txt does not define one. Also backfills the agency_id on the agency row itself. If agency.txt already defines an agency_id, that value takes precedence. Optional.
realtimeAlertsobjectAn 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.
realtimeTripUpdatesobjectAn 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.
realtimeVehiclePositionsobjectAn 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 databaseimport{importGtfs}from'gtfs';importDatabasefrom'better-sqlite3';constdb=newDatabase('/path/to/database');importGtfs({agencies: [{path: '/path/to/the/unzipped/gtfs/',},],db: db,});
// Using `openDb` from node-gtfs to open databaseimport{importGtfs,openDb}from'gtfs';constdb=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, defaults to 30000 (30 seconds).

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

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": 3600
}

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} Controls error handling behavior during GTFS import. When true, the import process will continue even when encountering errors, logging them instead of stopping execution. Defaults to false.

When enabled, ignoreErrors will:

  • Continue processing other GTFS files when one file fails
  • Log error messages instead of throwing exceptions
  • Skip problematic records within files while importing valid ones
  • Handle various error types including:
    • Invalid CSV data or malformed records
    • JSON parsing errors (for GeoJSON files)
    • Database constraint violations
    • File read/write errors
    • GTFS-Realtime API failures

Use cases:

  • Importing from multiple GTFS sources where some may have data quality issues
  • Processing large datasets where minor errors shouldn't halt the entire import
  • Development/testing scenarios where you want to see all errors at once

⚠️ Important considerations:

  • Errors are logged but not thrown, so you may miss critical data issues
  • Partial imports may result in incomplete or inconsistent data
  • Consider using the exclude config option to skip problematic files entirely instead of ignoring errors
{
"agencies": [
{
"path": "/path/to/the/unzipped/gtfs/"
}
],
"ignoreErrors": true
}

includeImportReport

{Boolean} When true, importGtfs() returns an ImportReport object containing details about the import (record counts, errors encountered, etc.) instead of returning void. Useful when combined with ignoreErrors: true to inspect what failed after a partial import. Defaults to false.

import{importGtfs}from'gtfs';constreport=awaitimportGtfs({agencies: [{path: '/path/to/gtfs'}],ignoreErrors: true,includeImportReport: true,});console.log(report.errors);

sqlitePath

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

"sqlitePath": "/tmp/gtfs.sqlite"

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';constconfig={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 somewhereconsole.log(text);},};awaitimportGtfs(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';importpathfrom'node:path';constconfig=JSON.parse(awaitreadFile(path.join(import.meta.dirname,'config.json'),'utf8'));awaitimportGtfs(config);

Configuration can be a JSON object in your code

import{importGtfs}from'gtfs';constconfig={sqlitePath: '/tmp/gtfs.sqlite',agencies: [{url: 'https://www.bart.gov/dev/schedules/google_transit.zip',exclude: ['shapes'],},],};awaitimportGtfs(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';importpathfrom'node:path';constconfig=JSON.parse(awaitreadFile(path.join(import.meta.dirname,'config.json'),'utf8'));awaitupdateGtfsRealtime(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';constconfig={sqlitePath: '/tmp/gtfs.sqlite',agencies: [{url: 'https://www.bart.gov/dev/schedules/google_transit.zip',exclude: ['shapes'],},],};awaitexportGtfs(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';importpathfrom'node:path';constconfig=JSON.parse(awaitreadFile(path.join(import.meta.dirname,'config.json'),'utf8'));constdb=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';constdb=openDb(config);// Do some stuff here// Close database connection when done.closeDb(db);

Deleting a Database

You can use deleteDb to close and delete a database. For file-backed databases the file is removed from the filesystem. For in-memory databases (the default) the connection is closed and the internal reference is removed — no filesystem operation is performed.

import{deleteDb,openDb}from'gtfs';constdb=openDb(config);// Do some stuff here// Delete the databasedeleteDb(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';importpathfrom'node:path';constconfig=JSON.parse(awaitreadFile(path.join(import.meta.dirname,'config.json'),'utf8'));constdb=openDb(config);constroutes=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';importpathfrom'node:path';constconfig=JSON.parse(awaitreadFile(path.join(import.meta.dirname,'config.json'),'utf8'));constdb=openDb(config);consttrips=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';importpathfrom'node:path';constconfig=JSON.parse(awaitreadFile(path.join(import.meta.dirname,'config.json'),'utf8'));constdb=openDb(config);conststops=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 agenciesconstagencies=getAgencies();// Get a specific agencyconstagencies=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 areasconstareas=getAreas();// Get a specific areaconstareas=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 attributionsconstattributions=getAttributions();// Get a specific attributionconstattributions=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 rulesconstbookingRules=getBookingRules();// Get a specific booking ruleconstbookingRules=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_nameconstroutes=getRoutes({},[],[['route_short_name','ASC']]);// Get a specific routeconstroutes=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`. */constroutes=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 stopsconststops=getStops();// Get a specific stop by stop_idconststops=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`. */conststops=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`. */conststops=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`. */conststops=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. */conststops=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 geoJSONconststopsGeojson=getStopsAsGeoJSON();// Get all stops for a specific route as geoJSONconststopsGeojson=getStopsAsGeoJSON({route_id: 'Lo-16APR',});// Get all stops within a 1000m bounding box as geoJSONconststopsGeojson=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 stoptimesconststoptimes=getStoptimes();// Get all stoptimes for a specific stopconststoptimes=getStoptimes({stop_id: '70011',});// Get all stoptimes for a specific trip, sorted by stop_sequenceconststoptimes=getStoptimes({trip_id: '37a',},[],[['stop_sequence','ASC']],);// Get all stoptimes for a specific stop and service_idconststoptimes=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 service date. */conststoptimes=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. */conststoptimes=getStoptimes({stop_id: '70011',date: 20160704,start_time: '11:30:00',end_time: '11:45:00'});/* * ⚠️ By default, when using the `date` parameter in a query, it will NOT * include stoptimes for trips whose service date is the previous day but * whose stoptimes occur after midnight (i.e., times greater than 24:00:00 * in GTFS, such as 25:15:00 for 1:15 AM the next day). * * To retrieve all stoptimes for a calendar date including those from  * trips assigned to the previous service date but occurring after  * midnight: * 1. Call `getStoptimes` with the target date: * 2. Call `getStoptimes` with the previous date and `start_time: '24:00:00'`: * 3. Combine both results for a complete set of stoptimes for July 5th. * * This approach ensures you include: * - All stoptimes for trips whose service date is July 4th but whose  * stoptimes occur after midnight (i.e., in the early hours of July 5th) * - All stoptimes for trips whose service date is July 5th (which can  * include trips with stoptimes that occur on July 6th after midnight ) */conststoptimesToday=getStoptimes({date: 20240705});conststoptimesYesterdayAfterMidnight=getStoptimes({date: 20240704,start_time: '24:00:00'})constmergedStoptimes=[
...stoptimesToday,
...stoptimesYesterdayAfterMidnight];

getTrips(query, fields, sortBy, options)

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

import{getTrips}from'gtfs';// Get all tripsconsttrips=getTrips();// Get trips for a specific route and directionconsttrips=getTrips({route_id: 'Lo-16APR',direction_id: 0});// Get trips for direction '' or nullconsttrips=getTrips({route_id: 'Lo-16APR',direction_id: null});// Get trips for a specific route and direction limited by a service_idconsttrips=getTrips({route_id: 'Lo-16APR',direction_id: 0,service_id: 'CT-16APR-Caltrain-Weekday-01',});/* * `getTrips` allows passing a `date` in the query to return only trips  * for a specific service date. */consttrips=getTrips({route_id: 'Bu-16APR',date: 20170416});

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 agencyconstshapes=getShapes();/* * `getShapes` allows passing a `route_id` in the query and it will query * trips to find all shapes served by that `route_id`. */constshapes=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`. */constshapes=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`. */constshapes=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 agencyconstshapesGeojson=getShapesAsGeoJSON();// Get geoJSON of shapes for a specific routeconstshapesGeojson=getShapesAsGeoJSON({route_id: 'Lo-16APR',});// Get geoJSON of shapes for a specific tripconstshapesGeojson=getShapesAsGeoJSON({trip_id: '37a',});// Get geoJSON of shapes for a specific `service_id`constshapesGeojson=getShapesAsGeoJSON({service_id: 'CT-16APR-Caltrain-Sunday-02',});// Get geoJSON of shapes for a specific `shape_id`constshapesGeojson=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 agencyconstcalendars=getCalendars();// Get calendars for a specific `service_id`constcalendars=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 dateconstserviceIds=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 agencyconstcalendarDates=getCalendarDates();// Get calendar_dates for a specific `service_id`constcalendarDates=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 agencyconstfareAttributes=getFareAttributes();// Get `fare_attributes` for a specific `fare_id`constfareAttributes=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 rulesconstfareLegRules=getFareLegRules();// Get fare leg rules for a specific fare productconstfareLegRules=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 mediaconstgetFareMedia=getFareMedia();// Get a specific fare mediaconstfareMedia=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 productsconstfareProducts=getFareProducts();// Get a specific fare productconstfareProducts=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 agencyconstfareRules=getFareRules();// Get fare_rules for a specific routeconstfareRules=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 rulesconstfareTransferRules=getFareTransferRules();// Get a all fare transfer rules for a specific fare productconstfareTransferRules=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_infoconstfeedInfo=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 frequenciesconstfrequencies=getFrequencies();// Get frequencies for a specific tripconstfrequencies=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 levelsconstlevels=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 groupsconstlocationGroups=getLocationGroups();// Get a specific location groupconstlocationGroups=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 stopsconstlocationGroupStops=getLocationGroupStops();// Get location group stops for a specific stop_idconstlocationGroups=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 locationsconstlocations=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 pathwaysconstpathways=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 timeframesconsttimeframes=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 transfersconsttransfers=getTransfers();// Get transfers for a specific stopconsttransfers=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 translationsconsttranslations=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 areasconststopAreas=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 networksconstnetworks=getNetworks();// Get networks for a specific network_idconstnetworks=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_networksconstrouteNetworks=getRouteNetworks();// Get route_networks for a specific network_idconstrouteNetworks=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 agencyconsttimetables=getTimetables();// Get a specific timetableconsttimetables=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_ordersconsttimetableStopOrders=getTimetableStopOrders();// Get timetable_stop_orders for a specific timetableconsttimetableStopOrders=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 agencyconsttimetablePages=getTimetablePages();// Get a specific timetable_pageconsttimetablePages=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 agencyconsttimetableNotes=getTimetableNotes();// Get a specific timetable_noteconsttimetableNotes=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 agencyconsttimetableNotesReferences=getTimetableNotesReferences();// Get all timetable_notes_references for a specific timetableconsttimetableNotesReferences=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. Each alert includes a nested informed_entities array containing all related informed entities (stops, routes, trips) that the alert applies to. 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

Each alert has an informed_entities array containing all stops, routes, and trips the alert applies to. The active_period field is a JSON-serialised array of {start, end} Unix timestamp objects representing when the alert is active. The convenience fields start_time and end_time contain the start and end of the first active period (or null if none is set).

import{getServiceAlerts}from'gtfs';// Get all service alertsconstserviceAlerts=getServiceAlerts();// Get alerts affecting a specific stopconststopAlerts=getServiceAlerts({stop_id: 'STOP_ID'});// Get alerts affecting a specific routeconstrouteAlerts=getServiceAlerts({route_id: 'ROUTE_ID'});

getServiceAlertInformedEntities(query, fields, sortBy, options)

Returns an array of GTFS Realtime service alert informed entities that match query parameters. Each row represents a single entity (stop, route, trip, etc.) that a service alert applies to, linked back to its alert via alert_id. Use this for direct access to the service_alert_informed_entities table; use getServiceAlerts() to get alerts with all informed entities already nested.

More details on Service Alert Informed Entities

import{getServiceAlertInformedEntities}from'gtfs';// Get all service alert informed entitiesconstinformedEntities=getServiceAlertInformedEntities();// Get all informed entities for a specific alertconstinformedEntities=getServiceAlertInformedEntities({alert_id: 'some-alert-id'});

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 updatesconsttripUpdates=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 updatesconststopTimeUpdates=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 dataconstvehiclePositions=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 attributesconstcalendarAttributes=getCalendarAttributes();// Get calendar attributes for specific serviceconstcalendarAttributes=getCalendarAttributes({service_id: '1234',});

getDirections(query, fields, sortBy, options)

Returns an array of directions that match query parameters.

import{getDirections}from'gtfs';// Get all directionsconstdirections=getDirections();// Get directions for a specific routeconstdirections=getDirections({route_id: '1234',});// Get directions for a specific route and directionconstdirections=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 attributesconstrouteAttributes=getRouteAttributes();// Get route attributes for specific routeconstrouteAttributes=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 attributesconststopAttributes=getStopAttributes();// Get stop attributes for specific stopconststopAttributes=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_alightconstboardAlights=getBoardAlights();// Get board_alight for a specific tripconstboardAlights=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_infoconstrideFeedInfos=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_tripconstriderTrips=getRiderTrips();// Get rider_trip for a specific tripconstriderTrips=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 ridershipconstriderships=getRidership();// Get ridership for a specific routeconstriderships=getRidership({route_id: '123',});

getRiderCategories(query, fields, sortBy, options)

Returns an array of rider categories that match query parameters. Details on rider_categories.txt

import{getRiderCategories}from'gtfs';// Get all rider categoriesconstriderCategories=getRiderCategories();// Get a specific rider categoryconstriderCategories=getRiderCategories({rider_category_id: '1',});

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_capacityconsttripCapacities=getTripCapacities();// Get trip_capacity for a specific tripconsttripCapacities=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 deadheadsconstdeadheads=getDeadheads();// Get deadheads for a specific blockconstdeadheads=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_timesconstdeadheadTimes=getDeadheadTimes();// Get deadhead_times for a specific deadheadconstdeadheadTimes=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_locationsconstopsLocations=getOpsLocations();// Get a specific ops_locationsconstopsLocations=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_piecesconstrunsPieces=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_eventsconstrunEvents=getRunEvents();// Get run_events for a specific piececonstrunEvents=getRunEvents({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_journeyconsttripsDatedVehicleJourneys=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.constadvancedQueryOptions={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',},],};conststoptimes=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';constdb=openDb(config);// Get a specific tripconsttrip=db.prepare('SELECT * FROM trips WHERE trip_id = ?').get('123');// Get all stopsconststops=db.prepare('SELECT * from stops').all();// Get all calendar_ids for specific dateconstcalendarIds=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 tablesconststopIds=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 SQLconstsql="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

About

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

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Auto-enable theater mode on YouTube (function() { function tryTheater() { var btn = document.querySelector('button[aria-label="Theater mode"], ytd-player #player button[title="Theater mode"]'); if (btn && !btn.classList.contains('activated')) { btn.click(); } } // Try immediately tryTheater(); // Try after navigation (SPA) var lastUrl = location.href; setInterval(function() { if (location.href !== lastUrl) { lastUrl = location.href; setTimeout(tryTheater, 500); } }, 1000); // Also try on player load var observer = new MutationObserver(tryTheater); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' GitHub - LACMTA/node-gtfs: Import GTFS transit data into SQLite and query routes, stops, times, fares and more. · GitHub
Skip to content

Repository files navigation

➡️ 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';importpathfrom'node:path';constconfig=JSON.parse(awaitreadFile(path.join(import.meta.dirname,'config.json'),'utf8'));try{awaitimportGtfs(config);}catch(error){console.error(error);}

Example Applications

GTFS-to-HTMLGTFS-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-geojsonGTFS-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-ChartGTFS-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 ValidatorGTFS 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-TTSGTFS-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 WidgetTransit Departures Widget creates a realtime transit departures widget from GTFS and GTFS-Realtime data.
GTFS-to-BlocksGTFS-to-Blocks reads transit data from GTFS and exports all trip segments sorted by block_id and their departure times in CSV format.

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
optiontypedescription
agenciesarrayAn array of GTFS files to be imported, and which files to exclude.
csvOptionsobjectOptions passed to csv-parse for parsing GTFS CSV files. Optional.
dbdatabase instanceAn existing database instance to use instead of relying on node-gtfs to connect. Optional.
downloadTimeoutintegerThe number of milliseconds to wait before throwing an error when downloading GTFS. Optional.
exportPathstringA path to a directory to put exported GTFS files. Optional, defaults to gtfs-export/<agency_name>.
gtfsRealtimeExpirationSecondsintegerAmount of time in seconds to allow GTFS-Realtime data to be stored in database before allowing to be deleted. Optional, defaults to 0.
ignoreDuplicatesbooleanWhether or not to ignore unique constraints on ids when importing GTFS, such as trip_id, calendar_id. Optional, defaults to false.
ignoreErrorsbooleanWhether or not to ignore errors during the import process. If true, failed files will be skipped while the rest are processed. Optional, defaults to false.
includeImportReportbooleanWhether to return a report object from importGtfs() containing details about what was imported and any errors encountered. Optional, defaults to false.
sqlitePathstringA path to a SQLite database. Optional, defaults to using an in-memory database.
verbosebooleanWhether 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

optiontypedescription
urlstringThe URL to a zipped GTFS file. Required if path not present.
pathstringA path to a zipped GTFS file or a directory of unzipped .txt files. Required if url is not present.
headersobjectAn object of HTTP headers in key:value format to use when fetching GTFS from the url specified. Optional.
prefixstringA prefix to be added to every ID field maintain uniqueness when importing multiple GTFS from multiple agencies. Optional.
excludearrayAn array of GTFS file names (without .txt) to exclude when importing. Optional.
fillEmptyAgencyIdbooleanWhen true, fills empty agency_id on routes, fares, and other files for single-agency feeds. Useful for shared databases. Defaults to false. Optional.
agencyIdstringExplicit agency_id to use when fillEmptyAgencyId is true and agency.txt does not define one. Also backfills the agency_id on the agency row itself. If agency.txt already defines an agency_id, that value takes precedence. Optional.
realtimeAlertsobjectAn 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.
realtimeTripUpdatesobjectAn 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.
realtimeVehiclePositionsobjectAn 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 databaseimport{importGtfs}from'gtfs';importDatabasefrom'better-sqlite3';constdb=newDatabase('/path/to/database');importGtfs({agencies: [{path: '/path/to/the/unzipped/gtfs/',},],db: db,});
// Using `openDb` from node-gtfs to open databaseimport{importGtfs,openDb}from'gtfs';constdb=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, defaults to 30000 (30 seconds).

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

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": 3600
}

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} Controls error handling behavior during GTFS import. When true, the import process will continue even when encountering errors, logging them instead of stopping execution. Defaults to false.

When enabled, ignoreErrors will:

  • Continue processing other GTFS files when one file fails
  • Log error messages instead of throwing exceptions
  • Skip problematic records within files while importing valid ones
  • Handle various error types including:
    • Invalid CSV data or malformed records
    • JSON parsing errors (for GeoJSON files)
    • Database constraint violations
    • File read/write errors
    • GTFS-Realtime API failures

Use cases:

  • Importing from multiple GTFS sources where some may have data quality issues
  • Processing large datasets where minor errors shouldn't halt the entire import
  • Development/testing scenarios where you want to see all errors at once

⚠️ Important considerations:

  • Errors are logged but not thrown, so you may miss critical data issues
  • Partial imports may result in incomplete or inconsistent data
  • Consider using the exclude config option to skip problematic files entirely instead of ignoring errors
{
"agencies": [
{
"path": "/path/to/the/unzipped/gtfs/"
}
],
"ignoreErrors": true
}

includeImportReport

{Boolean} When true, importGtfs() returns an ImportReport object containing details about the import (record counts, errors encountered, etc.) instead of returning void. Useful when combined with ignoreErrors: true to inspect what failed after a partial import. Defaults to false.

import{importGtfs}from'gtfs';constreport=awaitimportGtfs({agencies: [{path: '/path/to/gtfs'}],ignoreErrors: true,includeImportReport: true,});console.log(report.errors);

sqlitePath

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

"sqlitePath": "/tmp/gtfs.sqlite"

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';constconfig={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 somewhereconsole.log(text);},};awaitimportGtfs(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';importpathfrom'node:path';constconfig=JSON.parse(awaitreadFile(path.join(import.meta.dirname,'config.json'),'utf8'));awaitimportGtfs(config);

Configuration can be a JSON object in your code

import{importGtfs}from'gtfs';constconfig={sqlitePath: '/tmp/gtfs.sqlite',agencies: [{url: 'https://www.bart.gov/dev/schedules/google_transit.zip',exclude: ['shapes'],},],};awaitimportGtfs(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';importpathfrom'node:path';constconfig=JSON.parse(awaitreadFile(path.join(import.meta.dirname,'config.json'),'utf8'));awaitupdateGtfsRealtime(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';constconfig={sqlitePath: '/tmp/gtfs.sqlite',agencies: [{url: 'https://www.bart.gov/dev/schedules/google_transit.zip',exclude: ['shapes'],},],};awaitexportGtfs(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';importpathfrom'node:path';constconfig=JSON.parse(awaitreadFile(path.join(import.meta.dirname,'config.json'),'utf8'));constdb=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';constdb=openDb(config);// Do some stuff here// Close database connection when done.closeDb(db);

Deleting a Database

You can use deleteDb to close and delete a database. For file-backed databases the file is removed from the filesystem. For in-memory databases (the default) the connection is closed and the internal reference is removed — no filesystem operation is performed.

import{deleteDb,openDb}from'gtfs';constdb=openDb(config);// Do some stuff here// Delete the databasedeleteDb(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';importpathfrom'node:path';constconfig=JSON.parse(awaitreadFile(path.join(import.meta.dirname,'config.json'),'utf8'));constdb=openDb(config);constroutes=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';importpathfrom'node:path';constconfig=JSON.parse(awaitreadFile(path.join(import.meta.dirname,'config.json'),'utf8'));constdb=openDb(config);consttrips=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';importpathfrom'node:path';constconfig=JSON.parse(awaitreadFile(path.join(import.meta.dirname,'config.json'),'utf8'));constdb=openDb(config);conststops=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 agenciesconstagencies=getAgencies();// Get a specific agencyconstagencies=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 areasconstareas=getAreas();// Get a specific areaconstareas=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 attributionsconstattributions=getAttributions();// Get a specific attributionconstattributions=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 rulesconstbookingRules=getBookingRules();// Get a specific booking ruleconstbookingRules=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_nameconstroutes=getRoutes({},[],[['route_short_name','ASC']]);// Get a specific routeconstroutes=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`. */constroutes=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 stopsconststops=getStops();// Get a specific stop by stop_idconststops=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`. */conststops=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`. */conststops=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`. */conststops=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. */conststops=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 geoJSONconststopsGeojson=getStopsAsGeoJSON();// Get all stops for a specific route as geoJSONconststopsGeojson=getStopsAsGeoJSON({route_id: 'Lo-16APR',});// Get all stops within a 1000m bounding box as geoJSONconststopsGeojson=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 stoptimesconststoptimes=getStoptimes();// Get all stoptimes for a specific stopconststoptimes=getStoptimes({stop_id: '70011',});// Get all stoptimes for a specific trip, sorted by stop_sequenceconststoptimes=getStoptimes({trip_id: '37a',},[],[['stop_sequence','ASC']],);// Get all stoptimes for a specific stop and service_idconststoptimes=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 service date. */conststoptimes=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. */conststoptimes=getStoptimes({stop_id: '70011',date: 20160704,start_time: '11:30:00',end_time: '11:45:00'});/* * ⚠️ By default, when using the `date` parameter in a query, it will NOT * include stoptimes for trips whose service date is the previous day but * whose stoptimes occur after midnight (i.e., times greater than 24:00:00 * in GTFS, such as 25:15:00 for 1:15 AM the next day). * * To retrieve all stoptimes for a calendar date including those from  * trips assigned to the previous service date but occurring after  * midnight: * 1. Call `getStoptimes` with the target date: * 2. Call `getStoptimes` with the previous date and `start_time: '24:00:00'`: * 3. Combine both results for a complete set of stoptimes for July 5th. * * This approach ensures you include: * - All stoptimes for trips whose service date is July 4th but whose  * stoptimes occur after midnight (i.e., in the early hours of July 5th) * - All stoptimes for trips whose service date is July 5th (which can  * include trips with stoptimes that occur on July 6th after midnight ) */conststoptimesToday=getStoptimes({date: 20240705});conststoptimesYesterdayAfterMidnight=getStoptimes({date: 20240704,start_time: '24:00:00'})constmergedStoptimes=[
...stoptimesToday,
...stoptimesYesterdayAfterMidnight];

getTrips(query, fields, sortBy, options)

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

import{getTrips}from'gtfs';// Get all tripsconsttrips=getTrips();// Get trips for a specific route and directionconsttrips=getTrips({route_id: 'Lo-16APR',direction_id: 0});// Get trips for direction '' or nullconsttrips=getTrips({route_id: 'Lo-16APR',direction_id: null});// Get trips for a specific route and direction limited by a service_idconsttrips=getTrips({route_id: 'Lo-16APR',direction_id: 0,service_id: 'CT-16APR-Caltrain-Weekday-01',});/* * `getTrips` allows passing a `date` in the query to return only trips  * for a specific service date. */consttrips=getTrips({route_id: 'Bu-16APR',date: 20170416});

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 agencyconstshapes=getShapes();/* * `getShapes` allows passing a `route_id` in the query and it will query * trips to find all shapes served by that `route_id`. */constshapes=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`. */constshapes=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`. */constshapes=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 agencyconstshapesGeojson=getShapesAsGeoJSON();// Get geoJSON of shapes for a specific routeconstshapesGeojson=getShapesAsGeoJSON({route_id: 'Lo-16APR',});// Get geoJSON of shapes for a specific tripconstshapesGeojson=getShapesAsGeoJSON({trip_id: '37a',});// Get geoJSON of shapes for a specific `service_id`constshapesGeojson=getShapesAsGeoJSON({service_id: 'CT-16APR-Caltrain-Sunday-02',});// Get geoJSON of shapes for a specific `shape_id`constshapesGeojson=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 agencyconstcalendars=getCalendars();// Get calendars for a specific `service_id`constcalendars=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 dateconstserviceIds=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 agencyconstcalendarDates=getCalendarDates();// Get calendar_dates for a specific `service_id`constcalendarDates=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 agencyconstfareAttributes=getFareAttributes();// Get `fare_attributes` for a specific `fare_id`constfareAttributes=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 rulesconstfareLegRules=getFareLegRules();// Get fare leg rules for a specific fare productconstfareLegRules=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 mediaconstgetFareMedia=getFareMedia();// Get a specific fare mediaconstfareMedia=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 productsconstfareProducts=getFareProducts();// Get a specific fare productconstfareProducts=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 agencyconstfareRules=getFareRules();// Get fare_rules for a specific routeconstfareRules=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 rulesconstfareTransferRules=getFareTransferRules();// Get a all fare transfer rules for a specific fare productconstfareTransferRules=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_infoconstfeedInfo=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 frequenciesconstfrequencies=getFrequencies();// Get frequencies for a specific tripconstfrequencies=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 levelsconstlevels=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 groupsconstlocationGroups=getLocationGroups();// Get a specific location groupconstlocationGroups=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 stopsconstlocationGroupStops=getLocationGroupStops();// Get location group stops for a specific stop_idconstlocationGroups=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 locationsconstlocations=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 pathwaysconstpathways=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 timeframesconsttimeframes=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 transfersconsttransfers=getTransfers();// Get transfers for a specific stopconsttransfers=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 translationsconsttranslations=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 areasconststopAreas=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 networksconstnetworks=getNetworks();// Get networks for a specific network_idconstnetworks=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_networksconstrouteNetworks=getRouteNetworks();// Get route_networks for a specific network_idconstrouteNetworks=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 agencyconsttimetables=getTimetables();// Get a specific timetableconsttimetables=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_ordersconsttimetableStopOrders=getTimetableStopOrders();// Get timetable_stop_orders for a specific timetableconsttimetableStopOrders=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 agencyconsttimetablePages=getTimetablePages();// Get a specific timetable_pageconsttimetablePages=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 agencyconsttimetableNotes=getTimetableNotes();// Get a specific timetable_noteconsttimetableNotes=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 agencyconsttimetableNotesReferences=getTimetableNotesReferences();// Get all timetable_notes_references for a specific timetableconsttimetableNotesReferences=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. Each alert includes a nested informed_entities array containing all related informed entities (stops, routes, trips) that the alert applies to. 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

Each alert has an informed_entities array containing all stops, routes, and trips the alert applies to. The active_period field is a JSON-serialised array of {start, end} Unix timestamp objects representing when the alert is active. The convenience fields start_time and end_time contain the start and end of the first active period (or null if none is set).

import{getServiceAlerts}from'gtfs';// Get all service alertsconstserviceAlerts=getServiceAlerts();// Get alerts affecting a specific stopconststopAlerts=getServiceAlerts({stop_id: 'STOP_ID'});// Get alerts affecting a specific routeconstrouteAlerts=getServiceAlerts({route_id: 'ROUTE_ID'});

getServiceAlertInformedEntities(query, fields, sortBy, options)

Returns an array of GTFS Realtime service alert informed entities that match query parameters. Each row represents a single entity (stop, route, trip, etc.) that a service alert applies to, linked back to its alert via alert_id. Use this for direct access to the service_alert_informed_entities table; use getServiceAlerts() to get alerts with all informed entities already nested.

More details on Service Alert Informed Entities

import{getServiceAlertInformedEntities}from'gtfs';// Get all service alert informed entitiesconstinformedEntities=getServiceAlertInformedEntities();// Get all informed entities for a specific alertconstinformedEntities=getServiceAlertInformedEntities({alert_id: 'some-alert-id'});

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 updatesconsttripUpdates=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 updatesconststopTimeUpdates=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 dataconstvehiclePositions=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 attributesconstcalendarAttributes=getCalendarAttributes();// Get calendar attributes for specific serviceconstcalendarAttributes=getCalendarAttributes({service_id: '1234',});

getDirections(query, fields, sortBy, options)

Returns an array of directions that match query parameters.

import{getDirections}from'gtfs';// Get all directionsconstdirections=getDirections();// Get directions for a specific routeconstdirections=getDirections({route_id: '1234',});// Get directions for a specific route and directionconstdirections=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 attributesconstrouteAttributes=getRouteAttributes();// Get route attributes for specific routeconstrouteAttributes=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 attributesconststopAttributes=getStopAttributes();// Get stop attributes for specific stopconststopAttributes=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_alightconstboardAlights=getBoardAlights();// Get board_alight for a specific tripconstboardAlights=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_infoconstrideFeedInfos=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_tripconstriderTrips=getRiderTrips();// Get rider_trip for a specific tripconstriderTrips=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 ridershipconstriderships=getRidership();// Get ridership for a specific routeconstriderships=getRidership({route_id: '123',});

getRiderCategories(query, fields, sortBy, options)

Returns an array of rider categories that match query parameters. Details on rider_categories.txt

import{getRiderCategories}from'gtfs';// Get all rider categoriesconstriderCategories=getRiderCategories();// Get a specific rider categoryconstriderCategories=getRiderCategories({rider_category_id: '1',});

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_capacityconsttripCapacities=getTripCapacities();// Get trip_capacity for a specific tripconsttripCapacities=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 deadheadsconstdeadheads=getDeadheads();// Get deadheads for a specific blockconstdeadheads=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_timesconstdeadheadTimes=getDeadheadTimes();// Get deadhead_times for a specific deadheadconstdeadheadTimes=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_locationsconstopsLocations=getOpsLocations();// Get a specific ops_locationsconstopsLocations=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_piecesconstrunsPieces=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_eventsconstrunEvents=getRunEvents();// Get run_events for a specific piececonstrunEvents=getRunEvents({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_journeyconsttripsDatedVehicleJourneys=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.constadvancedQueryOptions={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',},],};conststoptimes=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';constdb=openDb(config);// Get a specific tripconsttrip=db.prepare('SELECT * FROM trips WHERE trip_id = ?').get('123');// Get all stopsconststops=db.prepare('SELECT * from stops').all();// Get all calendar_ids for specific dateconstcalendarIds=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 tablesconststopIds=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 SQLconstsql="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

About

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

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Remove or un-stick sticky/fixed headers that block content (function() { function unstick() { document.querySelectorAll('header, nav, [role="banner"], .header, .navbar, .sticky, .fixed-top, [style*="position: fixed"], [style*="position:sticky"]').forEach(function(el) { if (el.style.position === 'fixed' || el.style.position === 'sticky' || getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') { el.style.position = 'static'; el.style.top = 'auto'; el.style.zIndex = 'auto'; } }); } unstick(); var observer = new MutationObserver(unstick); observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] }); })(); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' GitHub - LACMTA/node-gtfs: Import GTFS transit data into SQLite and query routes, stops, times, fares and more. · GitHub
Skip to content

Repository files navigation

➡️ 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';importpathfrom'node:path';constconfig=JSON.parse(awaitreadFile(path.join(import.meta.dirname,'config.json'),'utf8'));try{awaitimportGtfs(config);}catch(error){console.error(error);}

Example Applications

GTFS-to-HTMLGTFS-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-geojsonGTFS-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-ChartGTFS-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 ValidatorGTFS 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-TTSGTFS-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 WidgetTransit Departures Widget creates a realtime transit departures widget from GTFS and GTFS-Realtime data.
GTFS-to-BlocksGTFS-to-Blocks reads transit data from GTFS and exports all trip segments sorted by block_id and their departure times in CSV format.

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
optiontypedescription
agenciesarrayAn array of GTFS files to be imported, and which files to exclude.
csvOptionsobjectOptions passed to csv-parse for parsing GTFS CSV files. Optional.
dbdatabase instanceAn existing database instance to use instead of relying on node-gtfs to connect. Optional.
downloadTimeoutintegerThe number of milliseconds to wait before throwing an error when downloading GTFS. Optional.
exportPathstringA path to a directory to put exported GTFS files. Optional, defaults to gtfs-export/<agency_name>.
gtfsRealtimeExpirationSecondsintegerAmount of time in seconds to allow GTFS-Realtime data to be stored in database before allowing to be deleted. Optional, defaults to 0.
ignoreDuplicatesbooleanWhether or not to ignore unique constraints on ids when importing GTFS, such as trip_id, calendar_id. Optional, defaults to false.
ignoreErrorsbooleanWhether or not to ignore errors during the import process. If true, failed files will be skipped while the rest are processed. Optional, defaults to false.
includeImportReportbooleanWhether to return a report object from importGtfs() containing details about what was imported and any errors encountered. Optional, defaults to false.
sqlitePathstringA path to a SQLite database. Optional, defaults to using an in-memory database.
verbosebooleanWhether 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

optiontypedescription
urlstringThe URL to a zipped GTFS file. Required if path not present.
pathstringA path to a zipped GTFS file or a directory of unzipped .txt files. Required if url is not present.
headersobjectAn object of HTTP headers in key:value format to use when fetching GTFS from the url specified. Optional.
prefixstringA prefix to be added to every ID field maintain uniqueness when importing multiple GTFS from multiple agencies. Optional.
excludearrayAn array of GTFS file names (without .txt) to exclude when importing. Optional.
fillEmptyAgencyIdbooleanWhen true, fills empty agency_id on routes, fares, and other files for single-agency feeds. Useful for shared databases. Defaults to false. Optional.
agencyIdstringExplicit agency_id to use when fillEmptyAgencyId is true and agency.txt does not define one. Also backfills the agency_id on the agency row itself. If agency.txt already defines an agency_id, that value takes precedence. Optional.
realtimeAlertsobjectAn 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.
realtimeTripUpdatesobjectAn 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.
realtimeVehiclePositionsobjectAn 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 databaseimport{importGtfs}from'gtfs';importDatabasefrom'better-sqlite3';constdb=newDatabase('/path/to/database');importGtfs({agencies: [{path: '/path/to/the/unzipped/gtfs/',},],db: db,});
// Using `openDb` from node-gtfs to open databaseimport{importGtfs,openDb}from'gtfs';constdb=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, defaults to 30000 (30 seconds).

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

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": 3600
}

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} Controls error handling behavior during GTFS import. When true, the import process will continue even when encountering errors, logging them instead of stopping execution. Defaults to false.

When enabled, ignoreErrors will:

  • Continue processing other GTFS files when one file fails
  • Log error messages instead of throwing exceptions
  • Skip problematic records within files while importing valid ones
  • Handle various error types including:
    • Invalid CSV data or malformed records
    • JSON parsing errors (for GeoJSON files)
    • Database constraint violations
    • File read/write errors
    • GTFS-Realtime API failures

Use cases:

  • Importing from multiple GTFS sources where some may have data quality issues
  • Processing large datasets where minor errors shouldn't halt the entire import
  • Development/testing scenarios where you want to see all errors at once

⚠️ Important considerations:

  • Errors are logged but not thrown, so you may miss critical data issues
  • Partial imports may result in incomplete or inconsistent data
  • Consider using the exclude config option to skip problematic files entirely instead of ignoring errors
{
"agencies": [
{
"path": "/path/to/the/unzipped/gtfs/"
}
],
"ignoreErrors": true
}

includeImportReport

{Boolean} When true, importGtfs() returns an ImportReport object containing details about the import (record counts, errors encountered, etc.) instead of returning void. Useful when combined with ignoreErrors: true to inspect what failed after a partial import. Defaults to false.

import{importGtfs}from'gtfs';constreport=awaitimportGtfs({agencies: [{path: '/path/to/gtfs'}],ignoreErrors: true,includeImportReport: true,});console.log(report.errors);

sqlitePath

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

"sqlitePath": "/tmp/gtfs.sqlite"

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';constconfig={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 somewhereconsole.log(text);},};awaitimportGtfs(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';importpathfrom'node:path';constconfig=JSON.parse(awaitreadFile(path.join(import.meta.dirname,'config.json'),'utf8'));awaitimportGtfs(config);

Configuration can be a JSON object in your code

import{importGtfs}from'gtfs';constconfig={sqlitePath: '/tmp/gtfs.sqlite',agencies: [{url: 'https://www.bart.gov/dev/schedules/google_transit.zip',exclude: ['shapes'],},],};awaitimportGtfs(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';importpathfrom'node:path';constconfig=JSON.parse(awaitreadFile(path.join(import.meta.dirname,'config.json'),'utf8'));awaitupdateGtfsRealtime(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';constconfig={sqlitePath: '/tmp/gtfs.sqlite',agencies: [{url: 'https://www.bart.gov/dev/schedules/google_transit.zip',exclude: ['shapes'],},],};awaitexportGtfs(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';importpathfrom'node:path';constconfig=JSON.parse(awaitreadFile(path.join(import.meta.dirname,'config.json'),'utf8'));constdb=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';constdb=openDb(config);// Do some stuff here// Close database connection when done.closeDb(db);

Deleting a Database

You can use deleteDb to close and delete a database. For file-backed databases the file is removed from the filesystem. For in-memory databases (the default) the connection is closed and the internal reference is removed — no filesystem operation is performed.

import{deleteDb,openDb}from'gtfs';constdb=openDb(config);// Do some stuff here// Delete the databasedeleteDb(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';importpathfrom'node:path';constconfig=JSON.parse(awaitreadFile(path.join(import.meta.dirname,'config.json'),'utf8'));constdb=openDb(config);constroutes=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';importpathfrom'node:path';constconfig=JSON.parse(awaitreadFile(path.join(import.meta.dirname,'config.json'),'utf8'));constdb=openDb(config);consttrips=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';importpathfrom'node:path';constconfig=JSON.parse(awaitreadFile(path.join(import.meta.dirname,'config.json'),'utf8'));constdb=openDb(config);conststops=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 agenciesconstagencies=getAgencies();// Get a specific agencyconstagencies=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 areasconstareas=getAreas();// Get a specific areaconstareas=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 attributionsconstattributions=getAttributions();// Get a specific attributionconstattributions=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 rulesconstbookingRules=getBookingRules();// Get a specific booking ruleconstbookingRules=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_nameconstroutes=getRoutes({},[],[['route_short_name','ASC']]);// Get a specific routeconstroutes=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`. */constroutes=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 stopsconststops=getStops();// Get a specific stop by stop_idconststops=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`. */conststops=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`. */conststops=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`. */conststops=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. */conststops=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 geoJSONconststopsGeojson=getStopsAsGeoJSON();// Get all stops for a specific route as geoJSONconststopsGeojson=getStopsAsGeoJSON({route_id: 'Lo-16APR',});// Get all stops within a 1000m bounding box as geoJSONconststopsGeojson=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 stoptimesconststoptimes=getStoptimes();// Get all stoptimes for a specific stopconststoptimes=getStoptimes({stop_id: '70011',});// Get all stoptimes for a specific trip, sorted by stop_sequenceconststoptimes=getStoptimes({trip_id: '37a',},[],[['stop_sequence','ASC']],);// Get all stoptimes for a specific stop and service_idconststoptimes=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 service date. */conststoptimes=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. */conststoptimes=getStoptimes({stop_id: '70011',date: 20160704,start_time: '11:30:00',end_time: '11:45:00'});/* * ⚠️ By default, when using the `date` parameter in a query, it will NOT * include stoptimes for trips whose service date is the previous day but * whose stoptimes occur after midnight (i.e., times greater than 24:00:00 * in GTFS, such as 25:15:00 for 1:15 AM the next day). * * To retrieve all stoptimes for a calendar date including those from  * trips assigned to the previous service date but occurring after  * midnight: * 1. Call `getStoptimes` with the target date: * 2. Call `getStoptimes` with the previous date and `start_time: '24:00:00'`: * 3. Combine both results for a complete set of stoptimes for July 5th. * * This approach ensures you include: * - All stoptimes for trips whose service date is July 4th but whose  * stoptimes occur after midnight (i.e., in the early hours of July 5th) * - All stoptimes for trips whose service date is July 5th (which can  * include trips with stoptimes that occur on July 6th after midnight ) */conststoptimesToday=getStoptimes({date: 20240705});conststoptimesYesterdayAfterMidnight=getStoptimes({date: 20240704,start_time: '24:00:00'})constmergedStoptimes=[
...stoptimesToday,
...stoptimesYesterdayAfterMidnight];

getTrips(query, fields, sortBy, options)

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

import{getTrips}from'gtfs';// Get all tripsconsttrips=getTrips();// Get trips for a specific route and directionconsttrips=getTrips({route_id: 'Lo-16APR',direction_id: 0});// Get trips for direction '' or nullconsttrips=getTrips({route_id: 'Lo-16APR',direction_id: null});// Get trips for a specific route and direction limited by a service_idconsttrips=getTrips({route_id: 'Lo-16APR',direction_id: 0,service_id: 'CT-16APR-Caltrain-Weekday-01',});/* * `getTrips` allows passing a `date` in the query to return only trips  * for a specific service date. */consttrips=getTrips({route_id: 'Bu-16APR',date: 20170416});

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 agencyconstshapes=getShapes();/* * `getShapes` allows passing a `route_id` in the query and it will query * trips to find all shapes served by that `route_id`. */constshapes=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`. */constshapes=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`. */constshapes=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 agencyconstshapesGeojson=getShapesAsGeoJSON();// Get geoJSON of shapes for a specific routeconstshapesGeojson=getShapesAsGeoJSON({route_id: 'Lo-16APR',});// Get geoJSON of shapes for a specific tripconstshapesGeojson=getShapesAsGeoJSON({trip_id: '37a',});// Get geoJSON of shapes for a specific `service_id`constshapesGeojson=getShapesAsGeoJSON({service_id: 'CT-16APR-Caltrain-Sunday-02',});// Get geoJSON of shapes for a specific `shape_id`constshapesGeojson=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 agencyconstcalendars=getCalendars();// Get calendars for a specific `service_id`constcalendars=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 dateconstserviceIds=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 agencyconstcalendarDates=getCalendarDates();// Get calendar_dates for a specific `service_id`constcalendarDates=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 agencyconstfareAttributes=getFareAttributes();// Get `fare_attributes` for a specific `fare_id`constfareAttributes=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 rulesconstfareLegRules=getFareLegRules();// Get fare leg rules for a specific fare productconstfareLegRules=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 mediaconstgetFareMedia=getFareMedia();// Get a specific fare mediaconstfareMedia=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 productsconstfareProducts=getFareProducts();// Get a specific fare productconstfareProducts=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 agencyconstfareRules=getFareRules();// Get fare_rules for a specific routeconstfareRules=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 rulesconstfareTransferRules=getFareTransferRules();// Get a all fare transfer rules for a specific fare productconstfareTransferRules=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_infoconstfeedInfo=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 frequenciesconstfrequencies=getFrequencies();// Get frequencies for a specific tripconstfrequencies=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 levelsconstlevels=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 groupsconstlocationGroups=getLocationGroups();// Get a specific location groupconstlocationGroups=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 stopsconstlocationGroupStops=getLocationGroupStops();// Get location group stops for a specific stop_idconstlocationGroups=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 locationsconstlocations=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 pathwaysconstpathways=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 timeframesconsttimeframes=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 transfersconsttransfers=getTransfers();// Get transfers for a specific stopconsttransfers=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 translationsconsttranslations=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 areasconststopAreas=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 networksconstnetworks=getNetworks();// Get networks for a specific network_idconstnetworks=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_networksconstrouteNetworks=getRouteNetworks();// Get route_networks for a specific network_idconstrouteNetworks=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 agencyconsttimetables=getTimetables();// Get a specific timetableconsttimetables=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_ordersconsttimetableStopOrders=getTimetableStopOrders();// Get timetable_stop_orders for a specific timetableconsttimetableStopOrders=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 agencyconsttimetablePages=getTimetablePages();// Get a specific timetable_pageconsttimetablePages=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 agencyconsttimetableNotes=getTimetableNotes();// Get a specific timetable_noteconsttimetableNotes=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 agencyconsttimetableNotesReferences=getTimetableNotesReferences();// Get all timetable_notes_references for a specific timetableconsttimetableNotesReferences=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. Each alert includes a nested informed_entities array containing all related informed entities (stops, routes, trips) that the alert applies to. 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

Each alert has an informed_entities array containing all stops, routes, and trips the alert applies to. The active_period field is a JSON-serialised array of {start, end} Unix timestamp objects representing when the alert is active. The convenience fields start_time and end_time contain the start and end of the first active period (or null if none is set).

import{getServiceAlerts}from'gtfs';// Get all service alertsconstserviceAlerts=getServiceAlerts();// Get alerts affecting a specific stopconststopAlerts=getServiceAlerts({stop_id: 'STOP_ID'});// Get alerts affecting a specific routeconstrouteAlerts=getServiceAlerts({route_id: 'ROUTE_ID'});

getServiceAlertInformedEntities(query, fields, sortBy, options)

Returns an array of GTFS Realtime service alert informed entities that match query parameters. Each row represents a single entity (stop, route, trip, etc.) that a service alert applies to, linked back to its alert via alert_id. Use this for direct access to the service_alert_informed_entities table; use getServiceAlerts() to get alerts with all informed entities already nested.

More details on Service Alert Informed Entities

import{getServiceAlertInformedEntities}from'gtfs';// Get all service alert informed entitiesconstinformedEntities=getServiceAlertInformedEntities();// Get all informed entities for a specific alertconstinformedEntities=getServiceAlertInformedEntities({alert_id: 'some-alert-id'});

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 updatesconsttripUpdates=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 updatesconststopTimeUpdates=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 dataconstvehiclePositions=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 attributesconstcalendarAttributes=getCalendarAttributes();// Get calendar attributes for specific serviceconstcalendarAttributes=getCalendarAttributes({service_id: '1234',});

getDirections(query, fields, sortBy, options)

Returns an array of directions that match query parameters.

import{getDirections}from'gtfs';// Get all directionsconstdirections=getDirections();// Get directions for a specific routeconstdirections=getDirections({route_id: '1234',});// Get directions for a specific route and directionconstdirections=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 attributesconstrouteAttributes=getRouteAttributes();// Get route attributes for specific routeconstrouteAttributes=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 attributesconststopAttributes=getStopAttributes();// Get stop attributes for specific stopconststopAttributes=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_alightconstboardAlights=getBoardAlights();// Get board_alight for a specific tripconstboardAlights=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_infoconstrideFeedInfos=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_tripconstriderTrips=getRiderTrips();// Get rider_trip for a specific tripconstriderTrips=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 ridershipconstriderships=getRidership();// Get ridership for a specific routeconstriderships=getRidership({route_id: '123',});

getRiderCategories(query, fields, sortBy, options)

Returns an array of rider categories that match query parameters. Details on rider_categories.txt

import{getRiderCategories}from'gtfs';// Get all rider categoriesconstriderCategories=getRiderCategories();// Get a specific rider categoryconstriderCategories=getRiderCategories({rider_category_id: '1',});

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_capacityconsttripCapacities=getTripCapacities();// Get trip_capacity for a specific tripconsttripCapacities=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 deadheadsconstdeadheads=getDeadheads();// Get deadheads for a specific blockconstdeadheads=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_timesconstdeadheadTimes=getDeadheadTimes();// Get deadhead_times for a specific deadheadconstdeadheadTimes=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_locationsconstopsLocations=getOpsLocations();// Get a specific ops_locationsconstopsLocations=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_piecesconstrunsPieces=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_eventsconstrunEvents=getRunEvents();// Get run_events for a specific piececonstrunEvents=getRunEvents({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_journeyconsttripsDatedVehicleJourneys=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.constadvancedQueryOptions={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',},],};conststoptimes=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';constdb=openDb(config);// Get a specific tripconsttrip=db.prepare('SELECT * FROM trips WHERE trip_id = ?').get('123');// Get all stopsconststops=db.prepare('SELECT * from stops').all();// Get all calendar_ids for specific dateconstcalendarIds=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 tablesconststopIds=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 SQLconstsql="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

About

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

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Universal Dark Mode - works on any site (function() { var enabled = true; function applyDarkMode() { if (!enabled) return; // Create style element if it doesn't exist var style = document.getElementById('universal-dark-mode-style'); if (!style) { style = document.createElement('style'); style.id = 'universal-dark-mode-style'; document.head.appendChild(style); } // Dark mode CSS - inverts colors but preserves images/video style.textContent = ' /* Invert everything except media */ html { filter: invert(1) hue-rotate(180deg) !important; background: #1a1a2e !important; } /* Restore images, videos, iframes, canvas */ img, video, iframe, canvas, svg, picture, [style*="background-image"] { filter: invert(1) hue-rotate(180deg) !important; } /* Preserve specific elements that should not be inverted */ .no-dark-mode, .no-dark-mode *, [data-theme="light"], [data-theme="light"], .ace_editor, .ace_editor *, .CodeMirror, .CodeMirror *, .monaco-editor, .monaco-editor *, .markdown-body pre, .markdown-body pre *, .highlight, .highlight *, pre code, pre code * { filter: none !important; } /* Fix common UI elements */ .modal, .popup, .dropdown-menu, .tooltip, .popover { filter: invert(1) hue-rotate(180deg) !important; background: #2d2d44 !important; border-color: #444 !important; } /* Scrollbars */ ::-webkit-scrollbar { background: #1a1a2e !important; } ::-webkit-scrollbar-thumb { background: #444 !important; } ::-webkit-scrollbar-thumb:hover { background: #555 !important; } /* Selection */ ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; } ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; } '; } function removeDarkMode() { var style = document.getElementById('universal-dark-mode-style'); if (style) style.remove(); } // Toggle with Alt+Shift+D document.addEventListener('keydown', function(e) { if (e.altKey && e.shiftKey && e.key === 'D') { e.preventDefault(); enabled = !enabled; if (enabled) { applyDarkMode(); console.log('[Universal Dark Mode] Enabled'); } else { removeDarkMode(); console.log('[Universal Dark Mode] Disabled'); } } }); // Apply on load applyDarkMode(); // Re-apply on dynamic content var observer = new MutationObserver(function(mutations) { if (enabled && !document.getElementById('universal-dark-mode-style')) { applyDarkMode(); } }); observer.observe(document.head, { childList: true }); console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle'); })(); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })(); GitHub - LACMTA/node-gtfs: Import GTFS transit data into SQLite and query routes, stops, times, fares and more. · GitHub
Skip to content

Repository files navigation

➡️ 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';importpathfrom'node:path';constconfig=JSON.parse(awaitreadFile(path.join(import.meta.dirname,'config.json'),'utf8'));try{awaitimportGtfs(config);}catch(error){console.error(error);}

Example Applications

GTFS-to-HTMLGTFS-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-geojsonGTFS-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-ChartGTFS-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 ValidatorGTFS 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-TTSGTFS-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 WidgetTransit Departures Widget creates a realtime transit departures widget from GTFS and GTFS-Realtime data.
GTFS-to-BlocksGTFS-to-Blocks reads transit data from GTFS and exports all trip segments sorted by block_id and their departure times in CSV format.

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
optiontypedescription
agenciesarrayAn array of GTFS files to be imported, and which files to exclude.
csvOptionsobjectOptions passed to csv-parse for parsing GTFS CSV files. Optional.
dbdatabase instanceAn existing database instance to use instead of relying on node-gtfs to connect. Optional.
downloadTimeoutintegerThe number of milliseconds to wait before throwing an error when downloading GTFS. Optional.
exportPathstringA path to a directory to put exported GTFS files. Optional, defaults to gtfs-export/<agency_name>.
gtfsRealtimeExpirationSecondsintegerAmount of time in seconds to allow GTFS-Realtime data to be stored in database before allowing to be deleted. Optional, defaults to 0.
ignoreDuplicatesbooleanWhether or not to ignore unique constraints on ids when importing GTFS, such as trip_id, calendar_id. Optional, defaults to false.
ignoreErrorsbooleanWhether or not to ignore errors during the import process. If true, failed files will be skipped while the rest are processed. Optional, defaults to false.
includeImportReportbooleanWhether to return a report object from importGtfs() containing details about what was imported and any errors encountered. Optional, defaults to false.
sqlitePathstringA path to a SQLite database. Optional, defaults to using an in-memory database.
verbosebooleanWhether 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

optiontypedescription
urlstringThe URL to a zipped GTFS file. Required if path not present.
pathstringA path to a zipped GTFS file or a directory of unzipped .txt files. Required if url is not present.
headersobjectAn object of HTTP headers in key:value format to use when fetching GTFS from the url specified. Optional.
prefixstringA prefix to be added to every ID field maintain uniqueness when importing multiple GTFS from multiple agencies. Optional.
excludearrayAn array of GTFS file names (without .txt) to exclude when importing. Optional.
fillEmptyAgencyIdbooleanWhen true, fills empty agency_id on routes, fares, and other files for single-agency feeds. Useful for shared databases. Defaults to false. Optional.
agencyIdstringExplicit agency_id to use when fillEmptyAgencyId is true and agency.txt does not define one. Also backfills the agency_id on the agency row itself. If agency.txt already defines an agency_id, that value takes precedence. Optional.
realtimeAlertsobjectAn 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.
realtimeTripUpdatesobjectAn 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.
realtimeVehiclePositionsobjectAn 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 databaseimport{importGtfs}from'gtfs';importDatabasefrom'better-sqlite3';constdb=newDatabase('/path/to/database');importGtfs({agencies: [{path: '/path/to/the/unzipped/gtfs/',},],db: db,});
// Using `openDb` from node-gtfs to open databaseimport{importGtfs,openDb}from'gtfs';constdb=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, defaults to 30000 (30 seconds).

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

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": 3600
}

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} Controls error handling behavior during GTFS import. When true, the import process will continue even when encountering errors, logging them instead of stopping execution. Defaults to false.

When enabled, ignoreErrors will:

  • Continue processing other GTFS files when one file fails
  • Log error messages instead of throwing exceptions
  • Skip problematic records within files while importing valid ones
  • Handle various error types including:
    • Invalid CSV data or malformed records
    • JSON parsing errors (for GeoJSON files)
    • Database constraint violations
    • File read/write errors
    • GTFS-Realtime API failures

Use cases:

  • Importing from multiple GTFS sources where some may have data quality issues
  • Processing large datasets where minor errors shouldn't halt the entire import
  • Development/testing scenarios where you want to see all errors at once

⚠️ Important considerations:

  • Errors are logged but not thrown, so you may miss critical data issues
  • Partial imports may result in incomplete or inconsistent data
  • Consider using the exclude config option to skip problematic files entirely instead of ignoring errors
{
"agencies": [
{
"path": "/path/to/the/unzipped/gtfs/"
}
],
"ignoreErrors": true
}

includeImportReport

{Boolean} When true, importGtfs() returns an ImportReport object containing details about the import (record counts, errors encountered, etc.) instead of returning void. Useful when combined with ignoreErrors: true to inspect what failed after a partial import. Defaults to false.

import{importGtfs}from'gtfs';constreport=awaitimportGtfs({agencies: [{path: '/path/to/gtfs'}],ignoreErrors: true,includeImportReport: true,});console.log(report.errors);

sqlitePath

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

"sqlitePath": "/tmp/gtfs.sqlite"

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';constconfig={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 somewhereconsole.log(text);},};awaitimportGtfs(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';importpathfrom'node:path';constconfig=JSON.parse(awaitreadFile(path.join(import.meta.dirname,'config.json'),'utf8'));awaitimportGtfs(config);

Configuration can be a JSON object in your code

import{importGtfs}from'gtfs';constconfig={sqlitePath: '/tmp/gtfs.sqlite',agencies: [{url: 'https://www.bart.gov/dev/schedules/google_transit.zip',exclude: ['shapes'],},],};awaitimportGtfs(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';importpathfrom'node:path';constconfig=JSON.parse(awaitreadFile(path.join(import.meta.dirname,'config.json'),'utf8'));awaitupdateGtfsRealtime(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';constconfig={sqlitePath: '/tmp/gtfs.sqlite',agencies: [{url: 'https://www.bart.gov/dev/schedules/google_transit.zip',exclude: ['shapes'],},],};awaitexportGtfs(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';importpathfrom'node:path';constconfig=JSON.parse(awaitreadFile(path.join(import.meta.dirname,'config.json'),'utf8'));constdb=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';constdb=openDb(config);// Do some stuff here// Close database connection when done.closeDb(db);

Deleting a Database

You can use deleteDb to close and delete a database. For file-backed databases the file is removed from the filesystem. For in-memory databases (the default) the connection is closed and the internal reference is removed — no filesystem operation is performed.

import{deleteDb,openDb}from'gtfs';constdb=openDb(config);// Do some stuff here// Delete the databasedeleteDb(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';importpathfrom'node:path';constconfig=JSON.parse(awaitreadFile(path.join(import.meta.dirname,'config.json'),'utf8'));constdb=openDb(config);constroutes=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';importpathfrom'node:path';constconfig=JSON.parse(awaitreadFile(path.join(import.meta.dirname,'config.json'),'utf8'));constdb=openDb(config);consttrips=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';importpathfrom'node:path';constconfig=JSON.parse(awaitreadFile(path.join(import.meta.dirname,'config.json'),'utf8'));constdb=openDb(config);conststops=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 agenciesconstagencies=getAgencies();// Get a specific agencyconstagencies=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 areasconstareas=getAreas();// Get a specific areaconstareas=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 attributionsconstattributions=getAttributions();// Get a specific attributionconstattributions=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 rulesconstbookingRules=getBookingRules();// Get a specific booking ruleconstbookingRules=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_nameconstroutes=getRoutes({},[],[['route_short_name','ASC']]);// Get a specific routeconstroutes=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`. */constroutes=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 stopsconststops=getStops();// Get a specific stop by stop_idconststops=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`. */conststops=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`. */conststops=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`. */conststops=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. */conststops=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 geoJSONconststopsGeojson=getStopsAsGeoJSON();// Get all stops for a specific route as geoJSONconststopsGeojson=getStopsAsGeoJSON({route_id: 'Lo-16APR',});// Get all stops within a 1000m bounding box as geoJSONconststopsGeojson=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 stoptimesconststoptimes=getStoptimes();// Get all stoptimes for a specific stopconststoptimes=getStoptimes({stop_id: '70011',});// Get all stoptimes for a specific trip, sorted by stop_sequenceconststoptimes=getStoptimes({trip_id: '37a',},[],[['stop_sequence','ASC']],);// Get all stoptimes for a specific stop and service_idconststoptimes=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 service date. */conststoptimes=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. */conststoptimes=getStoptimes({stop_id: '70011',date: 20160704,start_time: '11:30:00',end_time: '11:45:00'});/* * ⚠️ By default, when using the `date` parameter in a query, it will NOT * include stoptimes for trips whose service date is the previous day but * whose stoptimes occur after midnight (i.e., times greater than 24:00:00 * in GTFS, such as 25:15:00 for 1:15 AM the next day). * * To retrieve all stoptimes for a calendar date including those from  * trips assigned to the previous service date but occurring after  * midnight: * 1. Call `getStoptimes` with the target date: * 2. Call `getStoptimes` with the previous date and `start_time: '24:00:00'`: * 3. Combine both results for a complete set of stoptimes for July 5th. * * This approach ensures you include: * - All stoptimes for trips whose service date is July 4th but whose  * stoptimes occur after midnight (i.e., in the early hours of July 5th) * - All stoptimes for trips whose service date is July 5th (which can  * include trips with stoptimes that occur on July 6th after midnight ) */conststoptimesToday=getStoptimes({date: 20240705});conststoptimesYesterdayAfterMidnight=getStoptimes({date: 20240704,start_time: '24:00:00'})constmergedStoptimes=[
...stoptimesToday,
...stoptimesYesterdayAfterMidnight];

getTrips(query, fields, sortBy, options)

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

import{getTrips}from'gtfs';// Get all tripsconsttrips=getTrips();// Get trips for a specific route and directionconsttrips=getTrips({route_id: 'Lo-16APR',direction_id: 0});// Get trips for direction '' or nullconsttrips=getTrips({route_id: 'Lo-16APR',direction_id: null});// Get trips for a specific route and direction limited by a service_idconsttrips=getTrips({route_id: 'Lo-16APR',direction_id: 0,service_id: 'CT-16APR-Caltrain-Weekday-01',});/* * `getTrips` allows passing a `date` in the query to return only trips  * for a specific service date. */consttrips=getTrips({route_id: 'Bu-16APR',date: 20170416});

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 agencyconstshapes=getShapes();/* * `getShapes` allows passing a `route_id` in the query and it will query * trips to find all shapes served by that `route_id`. */constshapes=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`. */constshapes=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`. */constshapes=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 agencyconstshapesGeojson=getShapesAsGeoJSON();// Get geoJSON of shapes for a specific routeconstshapesGeojson=getShapesAsGeoJSON({route_id: 'Lo-16APR',});// Get geoJSON of shapes for a specific tripconstshapesGeojson=getShapesAsGeoJSON({trip_id: '37a',});// Get geoJSON of shapes for a specific `service_id`constshapesGeojson=getShapesAsGeoJSON({service_id: 'CT-16APR-Caltrain-Sunday-02',});// Get geoJSON of shapes for a specific `shape_id`constshapesGeojson=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 agencyconstcalendars=getCalendars();// Get calendars for a specific `service_id`constcalendars=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 dateconstserviceIds=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 agencyconstcalendarDates=getCalendarDates();// Get calendar_dates for a specific `service_id`constcalendarDates=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 agencyconstfareAttributes=getFareAttributes();// Get `fare_attributes` for a specific `fare_id`constfareAttributes=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 rulesconstfareLegRules=getFareLegRules();// Get fare leg rules for a specific fare productconstfareLegRules=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 mediaconstgetFareMedia=getFareMedia();// Get a specific fare mediaconstfareMedia=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 productsconstfareProducts=getFareProducts();// Get a specific fare productconstfareProducts=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 agencyconstfareRules=getFareRules();// Get fare_rules for a specific routeconstfareRules=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 rulesconstfareTransferRules=getFareTransferRules();// Get a all fare transfer rules for a specific fare productconstfareTransferRules=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_infoconstfeedInfo=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 frequenciesconstfrequencies=getFrequencies();// Get frequencies for a specific tripconstfrequencies=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 levelsconstlevels=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 groupsconstlocationGroups=getLocationGroups();// Get a specific location groupconstlocationGroups=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 stopsconstlocationGroupStops=getLocationGroupStops();// Get location group stops for a specific stop_idconstlocationGroups=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 locationsconstlocations=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 pathwaysconstpathways=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 timeframesconsttimeframes=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 transfersconsttransfers=getTransfers();// Get transfers for a specific stopconsttransfers=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 translationsconsttranslations=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 areasconststopAreas=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 networksconstnetworks=getNetworks();// Get networks for a specific network_idconstnetworks=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_networksconstrouteNetworks=getRouteNetworks();// Get route_networks for a specific network_idconstrouteNetworks=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 agencyconsttimetables=getTimetables();// Get a specific timetableconsttimetables=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_ordersconsttimetableStopOrders=getTimetableStopOrders();// Get timetable_stop_orders for a specific timetableconsttimetableStopOrders=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 agencyconsttimetablePages=getTimetablePages();// Get a specific timetable_pageconsttimetablePages=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 agencyconsttimetableNotes=getTimetableNotes();// Get a specific timetable_noteconsttimetableNotes=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 agencyconsttimetableNotesReferences=getTimetableNotesReferences();// Get all timetable_notes_references for a specific timetableconsttimetableNotesReferences=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. Each alert includes a nested informed_entities array containing all related informed entities (stops, routes, trips) that the alert applies to. 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

Each alert has an informed_entities array containing all stops, routes, and trips the alert applies to. The active_period field is a JSON-serialised array of {start, end} Unix timestamp objects representing when the alert is active. The convenience fields start_time and end_time contain the start and end of the first active period (or null if none is set).

import{getServiceAlerts}from'gtfs';// Get all service alertsconstserviceAlerts=getServiceAlerts();// Get alerts affecting a specific stopconststopAlerts=getServiceAlerts({stop_id: 'STOP_ID'});// Get alerts affecting a specific routeconstrouteAlerts=getServiceAlerts({route_id: 'ROUTE_ID'});

getServiceAlertInformedEntities(query, fields, sortBy, options)

Returns an array of GTFS Realtime service alert informed entities that match query parameters. Each row represents a single entity (stop, route, trip, etc.) that a service alert applies to, linked back to its alert via alert_id. Use this for direct access to the service_alert_informed_entities table; use getServiceAlerts() to get alerts with all informed entities already nested.

More details on Service Alert Informed Entities

import{getServiceAlertInformedEntities}from'gtfs';// Get all service alert informed entitiesconstinformedEntities=getServiceAlertInformedEntities();// Get all informed entities for a specific alertconstinformedEntities=getServiceAlertInformedEntities({alert_id: 'some-alert-id'});

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 updatesconsttripUpdates=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 updatesconststopTimeUpdates=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 dataconstvehiclePositions=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 attributesconstcalendarAttributes=getCalendarAttributes();// Get calendar attributes for specific serviceconstcalendarAttributes=getCalendarAttributes({service_id: '1234',});

getDirections(query, fields, sortBy, options)

Returns an array of directions that match query parameters.

import{getDirections}from'gtfs';// Get all directionsconstdirections=getDirections();// Get directions for a specific routeconstdirections=getDirections({route_id: '1234',});// Get directions for a specific route and directionconstdirections=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 attributesconstrouteAttributes=getRouteAttributes();// Get route attributes for specific routeconstrouteAttributes=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 attributesconststopAttributes=getStopAttributes();// Get stop attributes for specific stopconststopAttributes=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_alightconstboardAlights=getBoardAlights();// Get board_alight for a specific tripconstboardAlights=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_infoconstrideFeedInfos=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_tripconstriderTrips=getRiderTrips();// Get rider_trip for a specific tripconstriderTrips=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 ridershipconstriderships=getRidership();// Get ridership for a specific routeconstriderships=getRidership({route_id: '123',});

getRiderCategories(query, fields, sortBy, options)

Returns an array of rider categories that match query parameters. Details on rider_categories.txt

import{getRiderCategories}from'gtfs';// Get all rider categoriesconstriderCategories=getRiderCategories();// Get a specific rider categoryconstriderCategories=getRiderCategories({rider_category_id: '1',});

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_capacityconsttripCapacities=getTripCapacities();// Get trip_capacity for a specific tripconsttripCapacities=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 deadheadsconstdeadheads=getDeadheads();// Get deadheads for a specific blockconstdeadheads=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_timesconstdeadheadTimes=getDeadheadTimes();// Get deadhead_times for a specific deadheadconstdeadheadTimes=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_locationsconstopsLocations=getOpsLocations();// Get a specific ops_locationsconstopsLocations=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_piecesconstrunsPieces=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_eventsconstrunEvents=getRunEvents();// Get run_events for a specific piececonstrunEvents=getRunEvents({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_journeyconsttripsDatedVehicleJourneys=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.constadvancedQueryOptions={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',},],};conststoptimes=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';constdb=openDb(config);// Get a specific tripconsttrip=db.prepare('SELECT * FROM trips WHERE trip_id = ?').get('123');// Get all stopsconststops=db.prepare('SELECT * from stops').all();// Get all calendar_ids for specific dateconstcalendarIds=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 tablesconststopIds=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 SQLconstsql="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

About

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

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages