DSN Parser
The `dsn-parser` package (currently at version 1.0.3) provides a fluent API for parsing and constructing database connection strings (DSNs). It supports common DSN formats, extracting components such as driver, user, password, host, port, database name, and query parameters. A primary use case demonstrated is parsing Heroku-style PostgreSQL environment variables (`pgsql://user:pass@host:port/database`) into an object format compatible with popular database drivers like `node-postgres`. The library can also be used to programmatically build DSNs from individual components, offering a concise way to manage database connection configurations. It is a focused utility library solely for DSN manipulation.
Common errors
-
TypeError: DSNParser is not a constructor
cause Attempting to use `import { DSNParser } from 'dsn-parser';` or incorrectly accessing the default export of a CommonJS module in an ES module context.fixIf in a CommonJS file, use `const DSNParser = require('dsn-parser');`. If in an ES module file, use `import DSNParser from 'dsn-parser';` and verify your build setup correctly handles CommonJS interop. -
ReferenceError: require is not defined
cause Trying to use `require('dsn-parser')` directly within an ES module (`.mjs` file or `type: 'module'` in `package.json`).fixChange the import statement to `import DSNParser from 'dsn-parser';` to use ES module syntax. Ensure your environment or bundler is configured to correctly handle CommonJS modules within an ESM project.
Warnings
- gotcha The `dsn-parser` package is implemented as a CommonJS module. Attempting to use `import` syntax without proper tooling (like a bundler or specific Node.js configuration) can lead to import errors in ES module contexts.
- gotcha The package has not been updated in over six years (last commit as of late 2023). While functional for its intended purpose, it may lack support for newer DSN formats, advanced parsing requirements, or security patches for potential vulnerabilities in its parsing logic.
Install
-
npm install dsn-parser -
yarn add dsn-parser -
pnpm add dsn-parser
Imports
- DSNParser
import DSNParser from 'dsn-parser';
const DSNParser = require('dsn-parser'); - DSNParser Class Instance
const dsn = DSNParser.parse('driver://...');const dsn = new DSNParser('driver://user:pass@host:port/db?key=value'); - Module Import (ESM context)
import { DSNParser } from 'dsn-parser';import DSNParser from 'dsn-parser'; // Requires a CommonJS interop wrapper or bundler
Quickstart
const DSNParser = require('dsn-parser');
const pg = require('pg'); // Example consumer, install 'pg' separately
// Simulate Heroku environment variable
process.env.HEROKU_POSTGRESQL_COPPER_URL = 'pgsql://user:pass@127.0.0.1:5432/my_db?sslmode=verify-full&application_name=myapp';
console.log('--- Parsing DSN ---');
// Parse the DSN string
const dsn = new DSNParser(process.env.HEROKU_POSTGRESQL_COPPER_URL);
const config = dsn.getParts();
console.log('Parsed DSN configuration:', config);
/*
Example output:
{
driver: 'pgsql',
user: 'user',
password: 'pass',
host: '127.0.0.1',
port: 5432,
database: 'my_db',
params: { sslmode: 'verify-full', application_name: 'myapp' }
}
*/
// This config object can then be used with database clients, e.g., node-postgres
// try {
// const pool = new pg.Pool(config);
// console.log('PG Pool config prepared. First client connect:', await pool.connect());
// await pool.end();
// } catch (error) {
// console.error('Failed to connect with pg:', error.message);
// }
console.log('\n--- Building DSN ---');
// Modify and rebuild a DSN
const newDsn = new DSNParser();
newDsn.set('driver', 'mysql')
.set('user', 'root')
.set('password', 'mysecurepass')
.set('host', 'localhost')
.set('port', 3306)
.set('database', 'my_application_db')
.set('params', {
charset: 'utf8mb4',
timezone: 'Z'
});
console.log('Built DSN string:', newDsn.getDSN());
// Expected output: mysql://root:mysecurepass@localhost:3306/my_application_db?charset=utf8mb4&timezone=Z