Neo4j JavaScript Driver

repository·6.x·Indexed 21 days ago

https://github.com/neo4j/neo4j-javascript-driver

The official Neo4j driver for JavaScript, providing connectivity to Neo4j databases via the Bolt protocol in Node.js (requires Node.js 18+) and WebSockets in web browsers. It includes the standard neo4j-driver, a lightweight neo4j-driver-lite version, and a preview driver for Deno. The driver handles 64-bit signed integers via a custom internal type to prevent precision loss and supports both Regular (Promises/Async-Await) and Reactive (Observables) sessions.

Tokens
16.9K
Snippets
65
Records
85
Agent score
74%

What's inside neo4j-javascript-driver

  1. Consume Records using different APIs

    6.x

    The driver supports three ways to consume query results:

    1. Promise API: The complete result set is collected before you can act on it. Best for standard async/await workflows.
    2. Streaming API (Subscriber): Records are processed lazily as they arrive from the database. This is useful for large result sets to reduce memory overhead. It uses callbacks like onNext, onCompleted, and onError.
    3. Reactive API: Uses Observables for a fully reactive stream of data. Best for integration with reactive programming patterns.
    // Promise API
    session.run('MATCH (n) RETURN n').then(result => {
      result.records.forEach(record => console.log(record.get(0)))
    })
    
    // Streaming API
    session.run('MATCH (n) RETURN n').subscribe({
      onNext: record => console.log(record.get(0)),
      onCompleted: () => session.close()
    })
    
    // Reactive API
    rxSession.run('MATCH (n) RETURN n').records().subscribe({
      next: record => console.log(record.get(0))
    })
  2. Handle Neo4j Integers and Numbers

    6.x

    Neo4j uses 64-bit signed integers, which can exceed the safe integer range of JavaScript (Number.MIN_SAFE_INTEGER to Number.MAX_SAFE_INTEGER). To prevent precision loss, the driver uses an internal integer type instead of native JavaScript numbers.

    Writing Integers

    Any JavaScript number passed as a parameter is treated as a Float. To write an integer, use neo4j.int(). For values outside the safe JavaScript range, pass the value as a string to neo4j.int().

    Reading Integers

    When reading values, check if they are within the safe range before converting to a native number using neo4j.integer.inSafeRange() and .toNumber(). For large integers, use .toString().

    Enabling Native Numbers (Lossy)

    You can configure the driver to return native JavaScript numbers for all integers by setting disableLossyIntegers: true in the driver configuration. Warning: This can result in loss of precision for integers outside the safe JavaScript range.

    // Writing integers
    session.run('CREATE (n {age: $myIntParam})', { myIntParam: neo4j.int(22) });
    session.run('CREATE (n {age: $myIntParam})', { myIntParam: neo4j.int('9223372036854775807') });
    
    // Reading integers safely
    var smallInteger = neo4j.int(123);
    if (neo4j.integer.inSafeRange(smallInteger)) {
      var aNumber = smallInteger.toNumber();
    }
    
    // Reading large integers as strings
    var largeInteger = neo4j.int('9223372036854775807');
    if (!neo4j.integer.inSafeRange(largeInteger)) {
      var integerAsString = largeInteger.toString();
    }
    
    // Configuring driver to return native (potentially lossy) numbers
    var driver = neo4j.driver(
      'neo4j://localhost',
      neo4j.auth.basic('neo4j', 'password'),
      { disableLossyIntegers: true }
    );
  3. Handle Neo4j Integers and JavaScript Numbers

    6.x

    Neo4j uses 64-bit signed integers, which can exceed the safe integer range of JavaScript (Number.MIN_SAFE_INTEGER to Number.MAX_SAFE_INTEGER). To prevent precision loss, the driver uses a custom internal integer type.

    Writing Integers

    Any JavaScript number passed as a parameter is treated as a Float. To write an integer, use neo4j.int():

    • Standard: neo4j.int(22)
    • Large Integers (via string): neo4j.int('9223372036854775807')

    Reading Integers

    When reading values, check if they are safe to convert to a native JavaScript number using neo4j.integer.inSafeRange().

    • Safe conversion: smallInteger.toNumber()
    • Unsafe (use string): largeInteger.toString()

    Enabling Native Numbers (Lossy Mode)

    You can configure the driver to return native JavaScript numbers instead of custom Integer objects by setting disableLossyIntegers: true. Warning: This can result in loss of precision for integers outside the safe JavaScript range.

    // Writing an integer
    session.run('CREATE (n {age: $myIntParam})', { myIntParam: neo4j.int(22) });
    
    // Reading an integer safely
    var smallInteger = neo4j.int(123);
    if (neo4j.integer.inSafeRange(smallInteger)) {
      var aNumber = smallInteger.toNumber();
    }
    
    // Configuring driver to use native numbers (potentially lossy)
    var driver = neo4j.driver(
      'neo4j://localhost',
      neo4j.auth.basic('neo4j', 'password'),
      { disableLossyIntegers: true }
    );
  4. Use the neo4j-driver instead of neo4j-driver-bolt-connection

    6.x

    The neo4j-driver-bolt-connection package is an internal module used by the neo4j-driver and neo4j-driver-lite packages to implement the Bolt Protocol. End users should not use this package directly. Instead, install and use one of the following official drivers:

    • neo4j-driver: The standard Neo4j Bolt Driver for JavaScript.
    • neo4j-driver-lite: A lightweight version of the driver.

    neo4j-driver-bolt-connection provides the underlying implementation of the Bolt Protocol using interfaces defined in neo4j-driver-core.

  5. Acquire a Session

    6.x

    Sessions are used to run Cypher statements. You can acquire either a Regular Session (using Promises/Async-Await) or a Reactive Session (using Observables).

    When acquiring a session, you can configure:

    • database: The specific database to target.
    • defaultAccessMode: Set to neo4j.session.READ or neo4j.session.WRITE.
    • bookmarks: An array of bookmarks to ensure causal consistency across sessions.

    Important: Always close your sessions when finished.

    // Regular Session examples
    var session = driver.session() // Default
    var session = driver.session({ defaultAccessMode: neo4j.session.READ })
    var session = driver.session({ bookmarks: [bookmark1, bookmark2] })
    var session = driver.session({ database: 'foo', defaultAccessMode: neo4j.session.WRITE })
    
    // Reactive Session examples
    var rxSession = driver.rxSession()
    var rxSession = driver.rxSession({ defaultAccessMode: neo4j.session.READ })
    var rxSession = driver.rxSession({ bookmarks: [bookmark1, bookmark2] })
    var rxSession = driver.rxSession({ database: 'foo', defaultAccessMode: neo4j.session.WRITE })
  6. Start the Deno-Specific Testkit Backend

    6.x

    To start the backend, you can use the direct deno run command from within the packages/testkit-backend/deno/ directory, or use the provided npm scripts from other locations.

    # From the packages/testkit-backend/deno/ directory:
    deno run --allow-read --allow-write --allow-net --allow-env --allow-run index.ts
    
    # Alternatively, from the testkit-backend root package:
    npm run start::deno
    
    # Alternatively, from the repository root folder:
    npm run start-testkit-backend::deno
  7. Configure and run tests using Testkit

    6.x

    Testkit is used to run tests against the Javascript Lite Driver. This setup requires Testkit 6, Python3, and Docker.

    Setup Steps

    1. Clone the Testkit repository: git clone https://github.com/neo4j-drivers/testkit.git
    2. Install Python requirements: pip3 install -r requirements.txt inside the Testkit folder.
    3. Configure environment variables to point to the driver repository.

    Environment Variables

    VariableDescription
    TEST_DRIVER_NAMESet to javascript
    TEST_DRIVER_REPOThe absolute path to the root folder of the driver repository
    TEST_DRIVER_LITESet to 1 to test neo4j-driver-lite
    TEST_DRIVER_DENOSet to 1 to test neo4j-driver-deno

    By default, Testkit runs against the full version of the driver.

    # 1. Clone Testkit
    $ git clone https://github.com/neo4j-drivers/testkit.git
    
    # 2. Install requirements
    $ pip3 install -r requirements.txt
    
    # 3. Configure environment
    $ export TEST_DRIVER_NAME=javascript
    $ export TEST_DRIVER_REPO=<path for the root folder of driver repository>
    
    # To test Lite driver specifically:
    $ export TEST_DRIVER_LITE=1
    
    # 4. Run tests
    $ python3 main.py
  8. Use the Neo4j Lite Driver for Deno

    6.x

    The Neo4j Lite Driver for Deno is a preview version of the official Neo4j driver, based on neo4j-driver-lite. It provides the same capabilities as the standard driver except for reactive sessions (it does not include RxJS or the Driver#rxSession API).

    To use the driver in a Deno application, import it from the Deno land URL. When running your application, you must provide appropriate permissions using Deno flags. For Deno versions below 1.27.1, use --allow-env instead of --allow-sys.

    import neo4j from "https://deno.land/x/neo4j_driver_lite@VERSION/mod.ts";
  9. Install and use the Neo4j Lite Driver for Deno

    6.x

    The Neo4j Lite Driver for Deno is a preview version based on neo4j-driver-lite. It provides the same capabilities as the standard Neo4j driver except for reactive sessions (it does not include RxJS or the Driver#rxSession API).

    To use it in a Deno application, import the driver from the Deno registry. When running your application, you must provide appropriate permissions using Deno flags.

    Required Deno Flags:

    • --allow-net
    • --allow-sys (For Deno versions below 1.27.1, use --allow-env instead of --allow-sys)

    Important: Always call await driver.close() when your application exits to prevent the process from hanging or exiting with a non-zero code.

    import neo4j from "https://deno.land/x/neo4j_driver_lite@VERSION/mod.ts";
    
    // ... usage ...
    
    await driver.close();
  10. Run unit tests for the Neo4j JavaScript Driver

    6.x

    Unit tests require the development environment to be set up as described in CONTRIBUTING.md. You can run tests for the entire project, a specific package, or use a watch mode for active development.

    Note: If changes span multiple packages, you may need to rebuild the project to propagate changes before running tests. The watch mode is not supported for the neo4j-driver package.

    # Run unit tests for the whole project
    $ npm run test::unit
    
    # Run unit tests for a specific module
    $ npm run test::unit -- --scope="name-of-the-package"
    
    # Run unit tests in watch mode for a specific package
    $ cd ./packages/name-of-package-folder
    $ npm run test::watch