All files / fs / eol.ts

83.33% Branches 5/6
93.75% Lines 15/16
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
 
 
 
 
x2
 
 
x2
 
 
 
 
 
 
 
 
 
 
 
x2
 
 
 
x2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
x2
x7
x7
x8
x8
x11
 
x7
x7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
x2
x12
x12




















I


















































// Copyright 2018-2025 the Deno authors. MIT license.
// This module is browser compatible.

/** End-of-line character for POSIX platforms such as macOS and Linux. */
export const LF = "\n" as const;

/** End-of-line character for Windows platforms. */
export const CRLF = "\r\n" as const;

/**
 * End-of-line character evaluated for the current platform.
 *
 * @example Usage
 * ```ts ignore
 * import { EOL } from "@std/fs/eol";
 *
 * EOL; // "\n" on POSIX platforms and "\r\n" on Windows
 * ```
 */
export const EOL: "\n" | "\r\n" =
  // deno-lint-ignore no-explicit-any
  (globalThis as any).Deno?.build.os === "windows" ? CRLF : LF;

const regDetect = /(?:\r?\n)/g;

/**
 * Returns the detected EOL character(s) detected in the input string. If no EOL
 * character is detected, `null` is returned.
 *
 * @param content The input string to detect EOL characters.
 *
 * @returns The detected EOL character(s) or `null` if no EOL character is detected.
 *
 * @example Usage
 * ```ts ignore
 * import { detect } from "@std/fs/eol";
 *
 * detect("deno\r\nis not\r\nnode"); // "\r\n"
 * detect("deno\nis not\r\nnode"); // "\r\n"
 * detect("deno\nis not\nnode"); // "\n"
 * detect("deno is not node"); // null
 * ```
 */
export function detect(content: string): typeof EOL | null {
  const d = content.match(regDetect);
  if (!d || d.length === 0) {
    return null;
  }
  const hasCRLF = d.some((x: string): boolean => x === CRLF);

  return hasCRLF ? CRLF : LF;
}

/**
 * Normalize the input string to the targeted EOL.
 *
 * @param content The input string to normalize.
 * @param eol The EOL character(s) to normalize the input string to.
 *
 * @returns The input string normalized to the targeted EOL.
 *
 * @example Usage
 * ```ts ignore
 * import { LF, format } from "@std/fs/eol";
 *
 * const CRLFinput = "deno\r\nis not\r\nnode";
 *
 * format(CRLFinput, LF); // "deno\nis not\nnode"
 * ```
 */
export function format(content: string, eol: typeof EOL): string {
  return content.replace(regDetect, eol);
}