| Total Complexity | 9 |
| Complexity/F | 9 |
| Lines of Code | 56 |
| Function Count | 1 |
| Duplicated Lines | 0 |
| Ratio | 0 % |
| Changes | 0 | ||
| 1 | import {promisify} from "util" |
||
| 2 | import {createReadStream, exists, open, writeFile, close, truncate } from 'fs' |
||
| 3 | import {createInterface} from 'readline' |
||
| 4 | |||
| 5 | const $exists = promisify(exists) |
||
| 6 | , $open = promisify(open) |
||
| 7 | , $write = promisify(writeFile) |
||
| 8 | , $truncate = promisify(truncate) |
||
| 9 | , $close = promisify(close) |
||
| 10 | |||
| 11 | export = rewrite |
||
| 12 | |||
| 13 | // TODO #12 with .trim() https://jsbench.me/fykmaajqmc/ |
||
| 14 | |||
| 15 | async function rewrite(filename: string, lines: string[], eol: string) { |
||
| 16 | const {length} = lines |
||
| 17 | , {length: eolLength} = eol |
||
| 18 | , fileExists = await $exists(filename) |
||
| 19 | |||
| 20 | let row = 0 |
||
| 21 | , position = 0 |
||
| 22 | |||
| 23 | if (fileExists) { |
||
| 24 | const lineReader = createInterface({ |
||
| 25 | input: createReadStream(filename), |
||
| 26 | crlfDelay: Infinity, |
||
| 27 | historySize: 0 |
||
| 28 | }) |
||
| 29 | |||
| 30 | let isSame = true |
||
| 31 | |||
| 32 | for await (const line of lineReader) { |
||
| 33 | if (line !== lines[row]) { |
||
| 34 | isSame = false |
||
| 35 | continue |
||
| 36 | } |
||
| 37 | row++ |
||
| 38 | position += line.length |
||
| 39 | } |
||
| 40 | |||
| 41 | lineReader.close() |
||
| 42 | |||
| 43 | if (isSame) { |
||
| 44 | if (lines[row] === "") |
||
| 45 | row++ |
||
| 46 | if (length === row) |
||
| 47 | return |
||
| 48 | } |
||
| 49 | |||
| 50 | await $truncate(filename, position + eolLength * (row - 1)) |
||
| 51 | } |
||
| 52 | |||
| 53 | const fd = await $open(filename, "a") |
||
| 54 | |||
| 55 | for (let i = row; i < length; i++) |
||
| 56 | await $write(fd, `${ |
||
| 57 | i ? eol : '' |
||
| 64 |