penv
A tiny loader for .env-style environment files, written in pure Dart.
penv reads a simple KEY=value file from disk and returns it as a Map<String, String>. If the file doesn't exist yet, it can generate a placeholder for you and tell you where to fill it in.
Features
- Supports comments (
#) and blank lines. - Strips optional single or double quotes around values.
- Optionally auto-creates a placeholder
.envfile (with your own template) on first run.
Installation
Add penv to your pubspec.yaml:
dependencies:
penv: ^1.0.0
Then run:
dart pub get
Usage
Create a .env file in your project root:
API_KEY=your-key-here
BASE_URL="https://example.com"
GREETING='hello world'
Load it:
import 'package:penv/penv.dart';
void main() {
final env = penvload('.env');
print(env['API_KEY']); // your-key-here
print(env['BASE_URL']); // https://example.com
print(env['GREETING']); // hello world
}
Handling a missing file
By default, if the file at path doesn't exist, penvload creates it with a
placeholder template and throws EnvFileNotFoundException so you notice and
fill it in:
import 'package:penv/penv.dart';
void main() {
try {
final env = penvload('.env');
print(env['API_KEY']);
} on EnvFileNotFoundException catch (e) {
print(e); // tells you a template file was created at the given path
}
}
You can supply your own placeholder content via template:
penvload(
'.env',
template: '''
# App configuration
API_KEY=
BASE_URL=
''',
);
If you'd rather penv not touch the filesystem when the file is missing,
pass createFile: false. In that case no file is written, and
EnvFileNotFoundException is thrown immediately:
penvload('.env', createFile: false);
API
penvload(String path, {String template, bool createFile = true})
Reads path and returns a Map<String, String> of the parsed key-value
pairs.
| Parameter | Type | Default | Description |
|---|---|---|---|
path |
String |
required | Path to the env file to read. |
template |
String |
a built-in placeholder | Content written to path if it doesn't exist and createFile is true. |
createFile |
bool |
true |
Whether to create a placeholder file when path doesn't exist. |
Throws EnvFileNotFoundException if no file exists at path.
Parsing rules
- Lines are trimmed before processing.
- Empty lines and lines starting with
#are ignored. - Lines without an
=are ignored. - The key is trimmed; empty keys are ignored.
- The value is trimmed; if it's fully wrapped in matching
'or"quotes, the quotes are stripped.
EnvFileNotFoundException
Thrown by penvload when path doesn't exist.
| Property | Type | Description |
|---|---|---|
path |
String |
The path that was looked up. |
createFile |
bool |
Whether a placeholder file was written to path before throwing. |
Contributing
Issues and pull requests are welcome at psdkjoon/penv.
License
Libraries
- penv
- A tiny, dependency-light loader for
.env-style environment files.