write-json-file
Advanced tools
Comparing version 4.1.1 to 4.2.0
42
index.js
@@ -13,2 +13,4 @@ 'use strict'; | ||
const hasTrailingNewline = file => /\n$/.test(file); | ||
const init = (fn, filePath, data, options) => { | ||
@@ -41,12 +43,16 @@ if (!filePath) { | ||
let {indent} = options; | ||
let trailingNewline = '\n'; | ||
try { | ||
const file = await readFile(filePath, 'utf8'); | ||
if (!hasTrailingNewline(file)) { | ||
trailingNewline = ''; | ||
} | ||
if (options.detectIndent) { | ||
try { | ||
const file = await readFile(filePath, 'utf8'); | ||
if (options.detectIndent) { | ||
indent = detectIndent(file).indent; | ||
} catch (error) { | ||
if (error.code !== 'ENOENT') { | ||
throw error; | ||
} | ||
} | ||
} catch (error) { | ||
if (error.code !== 'ENOENT') { | ||
throw error; | ||
} | ||
} | ||
@@ -56,3 +62,3 @@ | ||
return writeFileAtomic(filePath, `${json}\n`, {mode: options.mode}); | ||
return writeFileAtomic(filePath, `${json}${trailingNewline}`, {mode: options.mode}); | ||
}; | ||
@@ -62,12 +68,16 @@ | ||
let {indent} = options; | ||
let trailingNewline = '\n'; | ||
try { | ||
const file = fs.readFileSync(filePath, 'utf8'); | ||
if (!hasTrailingNewline(file)) { | ||
trailingNewline = ''; | ||
} | ||
if (options.detectIndent) { | ||
try { | ||
const file = fs.readFileSync(filePath, 'utf8'); | ||
if (options.detectIndent) { | ||
indent = detectIndent(file).indent; | ||
} catch (error) { | ||
if (error.code !== 'ENOENT') { | ||
throw error; | ||
} | ||
} | ||
} catch (error) { | ||
if (error.code !== 'ENOENT') { | ||
throw error; | ||
} | ||
} | ||
@@ -77,3 +87,3 @@ | ||
return writeFileAtomic.sync(filePath, `${json}\n`, {mode: options.mode}); | ||
return writeFileAtomic.sync(filePath, `${json}${trailingNewline}`, {mode: options.mode}); | ||
}; | ||
@@ -80,0 +90,0 @@ |
{ | ||
"name": "write-json-file", | ||
"version": "4.1.1", | ||
"version": "4.2.0", | ||
"description": "Stringify and write JSON to a file atomically", | ||
@@ -5,0 +5,0 @@ "license": "MIT", |
7506
140