Skip to content

Instantly share code, notes, and snippets.

@tkrotoff
Last active April 8, 2025 14:55
Show Gist options
  • Save tkrotoff/a2e39308a2a16df5f74d97d7fb7bf88d to your computer and use it in GitHub Desktop.
Save tkrotoff/a2e39308a2a16df5f74d97d7fb7bf88d to your computer and use it in GitHub Desktop.
Parse an env string (printenv output)
import assert from 'node:assert/strict';
/**
* Parses a string containing environment variables and returns a map of key => value pairs.
*
* The string format is `KEY=VALUE` pairs separated by new lines;
* it typically comes from UNIX command `printenv` or `env`.
*/
export function parseEnv(env: string) {
const lines = env
.split('\n')
// Trim lines
.map(line => line.trim())
// Remove empty lines
.filter(line => line !== '')
// Remove commented lines
.filter(line => !line.startsWith('#'));
const envMap = new Map();
for (const line of lines) {
const result = /^(.+)=(.*)$/.exec(line);
assert(result !== null, `Invalid line '${line}'`);
const key = result[1];
const value = result[2];
envMap.set(key, value);
}
return envMap;
}
import { expect, test } from 'vitest';
import { parseEnv } from './parseEnv';
test('parse printenv output', () => {
const env = `
SHELL=/bin/zsh
HOME=/Users/username
LOGNAME=username
USER=username
PATH=/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Library/Apple/usr/bin
# This is a comment
DOUBLE_QUOTES="value with double quotes"
SINGLE_QUOTES='value with single quotes'
NO_VALUE=
SPACES= value with spaces
EQUAL=value with = equal sign
HASH=value with # number sign
`;
expect(Object.fromEntries(parseEnv(env).entries())).toEqual({
SHELL: '/bin/zsh',
HOME: '/Users/username',
LOGNAME: 'username',
USER: 'username',
PATH: '/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Library/Apple/usr/bin',
DOUBLE_QUOTES: '"value with double quotes"',
SINGLE_QUOTES: "'value with single quotes'",
NO_VALUE: '',
SPACES: ' value with spaces',
'EQUAL=value with ': ' equal sign',
HASH: 'value with # number sign'
});
});
test('fail when parsing a malformed env string', () => {
expect(() => parseEnv(`=no key`)).toThrow("Invalid line '=no key'");
expect(() => parseEnv(`=`)).toThrow("Invalid line '='");
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment