npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@markusberg/key-value-parser

v0.3.0

Published

Simple key-value parser

Downloads

12

Readme

key-value-parser

This is a simple and versatile key=value parser. It's useful for parsing configuration files similar to dotenv, but without putting variables in your env.

Given a KEY=value string, this parser will strip comments and empty lines and return a plain javascript object. For example, given the following input:

# This is an example file

MONGODB_HOST=mymongohost.example.com
MONGODB_USER=username
MONGODB_PASSWORD=bingo # this is an inline comment

# If you need to preserve leading or trailing white space, you need to use quotes
WITH_WHITE_SPACE = ' Hello '

INFO_TEXT = 'This is a multiline
value. It can contain quotes other than the
quotes surrounding it; "double-quotes" for instance. Or you
can escape it: \' ' # this is a trailing comment

You will get the following object back:

{
  "MONGODB_HOST": "mymongohost.example.com",
  "MONGODB_USER": "username",
  "MONGODB_PASSWORD": "bingo",
  "WITH_WHITE_SPACE": " Hello ",
  "INFO_TEXT": `This is a multiline
value. It can contain quotes other than the
quotes surrounding it; "double-quotes" for instance. Or you
can escape it: ' `
}

Prerequisites

key-value-parser supports Node.JS version 18 and up, and is only available as an ES-module.

Usage

If you already have your key-values in a string, you can pass it tot the parse-function:

import { parse } from '@markusberg/key-value-parser'

const mydata = `
# This is an example file

MONGODB_HOST=mymongohost.example.com
MONGODB_USER=username
MONGODB_PASSWORD=bingo # this is an inline comment

`
const parsed = parse(mydata)

There's also a convenience function for loading and parsing a file from disk:

import { loadAndParse } from 'key-value-parser'

const myfile = '.env'
const parsed = loadAndParse(myfile)

Type safety

The parsed data is always in the form of Record<string, string>. If you want to add type safety, I highly recommend zod. Here's an example:

import { z } from 'zod'
import { loadAndParse } from '@markusberg/key-value-parser'

/**
 * Zod preprocessor
 * Accept strings, floats or ints, but output ints
 */
export const StringToIntSchema = z.preprocess((arg) => {
  if (typeof arg === 'number') {
    return Math.round(arg)
  } else if (typeof arg === 'string') {
    return parseInt(arg)
  }
  return arg
}, z.number().int())

// The expected schema
export const EnvSchema = z.object({
  SERVER_HOST: z.string(),
  SERVER_PORT: StringToIntSchema,
})

let env: z.infer<typeof EnvSchema>

try {
  const parsed = loadAndParse('.env')
  env = EnvSchema.parse(parsed)
  nodeEnv = NodeEnvSchema.parse(process.env.NODE_ENV)
} catch (error) {
  console.error('Error loading .env file')
  console.error(error)
  process.exit()
}

/***
 * The exported env is guaranteed to have the following shape:
 * {
 *   SERVER_HOST: string
 *   SERVER_PORT: number
 * }
 *
 * and SERVER_PORT is even guaranteed to be an integer
 */
export { env }