diff --git a/README.md b/README.md index 8dea161..8354ba7 100644 --- a/README.md +++ b/README.md @@ -86,6 +86,10 @@ The `options` object may contain the following: after a section header. Some INI file parsers (for example the TOSHIBA FlashAir one) need this to parse the file successfully. By default, the additional newline is omitted. +* `platform` String to define which platform this INI file is expected + to be used with: when `platform` is `win32`, line terminations are + CR+LF, for other platforms line termination is LF. By default the + current platform name is used. For backwards compatibility reasons, if a `string` options is passed in, then it is assumed to be the `section` value. diff --git a/lib/ini.js b/lib/ini.js index be5efb6..6bb2186 100644 --- a/lib/ini.js +++ b/lib/ini.js @@ -1,25 +1,19 @@ const { hasOwnProperty } = Object.prototype -/* istanbul ignore next */ -const eol = typeof process !== 'undefined' && - process.platform === 'win32' ? '\r\n' : '\n' - -const encode = (obj, opt) => { - const children = [] - let out = '' - +const encode = (obj, opt = {}) => { if (typeof opt === 'string') { - opt = { - section: opt, - whitespace: false, - } - } else { - opt = opt || Object.create(null) - opt.whitespace = opt.whitespace === true - opt.newline = opt.newline === true + opt = { section: opt } } + opt.whitespace = opt.whitespace === true + opt.newline = opt.newline === true + /* istanbul ignore next */ + opt.platform = opt.platform || process?.platform + /* istanbul ignore next */ + const eol = opt.platform === 'win32' ? '\r\n' : '\n' const separator = opt.whitespace ? ' = ' : '=' + const children = [] + let out = '' for (const k of Object.keys(obj)) { const val = obj[k] @@ -41,11 +35,9 @@ const encode = (obj, opt) => { for (const k of children) { const nk = dotSplit(k).join('\\.') const section = (opt.section ? opt.section + '.' : '') + nk - const { whitespace, newline } = opt const child = encode(obj[k], { + ...opt, section, - whitespace, - newline, }) if (out.length && child.length) { out += eol diff --git a/tap-snapshots/test/foo.js.test.cjs b/tap-snapshots/test/foo.js.test.cjs index c80ffdf..8bb048f 100644 --- a/tap-snapshots/test/foo.js.test.cjs +++ b/tap-snapshots/test/foo.js.test.cjs @@ -133,6 +133,18 @@ value=10 ` +exports[`test/foo.js TAP encode with platform=win32 > must match snapshot 1`] = ` +Array [ + "[log]", + "type=file", + "", + "[log.level]", + "label=debug", + "value=10", + "", +] +` + exports[`test/foo.js TAP encode with whitespace > must match snapshot 1`] = ` [log] type = file diff --git a/test/foo.js b/test/foo.js index 5e9c8c8..d65c60b 100644 --- a/test/foo.js +++ b/test/foo.js @@ -52,3 +52,11 @@ test('encode with newline', function (t) { t.matchSnapshot(e) t.end() }) + +test('encode with platform=win32', function (t) { + const obj = { log: { type: 'file', level: { label: 'debug', value: 10 } } } + const e = i.encode(obj, { platform: 'win32' }) + + t.matchSnapshot(e.split('\r\n')) + t.end() +})