deno.land / std@0.224.0 / dotenv / stringify.ts

stringify.ts
View Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.// This module is browser compatible.
/** * Stringify an object into a valid `.env` file format. * * @example * ```ts * import { stringify } from "https://deno.land/std@$STD_VERSION/dotenv/stringify.ts"; * * const object = { GREETING: "hello world" }; * const string = stringify(object); // GREETING='hello world' * ``` * * @param object object to be stringified * @returns string of object */export function stringify(object: Record<string, string>): string { const lines: string[] = []; for (const [key, value] of Object.entries(object)) { let quote;
let escapedValue = value ?? ""; if (key.startsWith("#")) { console.warn( `key starts with a '#' indicates a comment and is ignored: '${key}'`, ); continue; } else if (escapedValue.includes("\n")) { // escape inner new lines escapedValue = escapedValue.replaceAll("\n", "\\n"); quote = `"`; } else if (escapedValue.match(/\W/)) { quote = "'"; }
if (quote) { // escape inner quotes escapedValue = escapedValue.replaceAll(quote, `\\${quote}`); escapedValue = `${quote}${escapedValue}${quote}`; } const line = `${key}=${escapedValue}`; lines.push(line); } return lines.join("\n");}
std

Version Info

Tagged at
6 months ago