@@ -10,6 +10,8 @@ const isPlainObj = require('is-plain-obj');
1010
1111const readFile = promisify ( fs . readFile ) ;
1212
13+ const hasTrailingNewline = file => / \n $ / . test ( file ) ;
14+
1315const init = ( fn , filePath , data , options ) => {
1416 if ( ! filePath ) {
1517 throw new TypeError ( 'Expected a filepath' ) ;
@@ -37,40 +39,48 @@ const init = (fn, filePath, data, options) => {
3739
3840const main = async ( filePath , data , options ) => {
3941 let { indent} = options ;
42+ let trailingNewline = '\n' ;
43+ try {
44+ const file = await readFile ( filePath , 'utf8' ) ;
45+ if ( ! hasTrailingNewline ( file ) ) {
46+ trailingNewline = '' ;
47+ }
4048
41- if ( options . detectIndent ) {
42- try {
43- const file = await readFile ( filePath , 'utf8' ) ;
49+ if ( options . detectIndent ) {
4450 indent = detectIndent ( file ) . indent ;
45- } catch ( error ) {
46- if ( error . code !== 'ENOENT' ) {
47- throw error ;
48- }
51+ }
52+ } catch ( error ) {
53+ if ( error . code !== 'ENOENT' ) {
54+ throw error ;
4955 }
5056 }
5157
5258 const json = JSON . stringify ( data , options . replacer , indent ) ;
5359
54- return writeFileAtomic ( filePath , `${ json } \n ` , { mode : options . mode } ) ;
60+ return writeFileAtomic ( filePath , `${ json } ${ trailingNewline } ` , { mode : options . mode } ) ;
5561} ;
5662
5763const mainSync = ( filePath , data , options ) => {
5864 let { indent} = options ;
65+ let trailingNewline = '\n' ;
66+ try {
67+ const file = fs . readFileSync ( filePath , 'utf8' ) ;
68+ if ( ! hasTrailingNewline ( file ) ) {
69+ trailingNewline = '' ;
70+ }
5971
60- if ( options . detectIndent ) {
61- try {
62- const file = fs . readFileSync ( filePath , 'utf8' ) ;
72+ if ( options . detectIndent ) {
6373 indent = detectIndent ( file ) . indent ;
64- } catch ( error ) {
65- if ( error . code !== 'ENOENT' ) {
66- throw error ;
67- }
74+ }
75+ } catch ( error ) {
76+ if ( error . code !== 'ENOENT' ) {
77+ throw error ;
6878 }
6979 }
7080
7181 const json = JSON . stringify ( data , options . replacer , indent ) ;
7282
73- return writeFileAtomic . sync ( filePath , `${ json } \n ` , { mode : options . mode } ) ;
83+ return writeFileAtomic . sync ( filePath , `${ json } ${ trailingNewline } ` , { mode : options . mode } ) ;
7484} ;
7585
7686module . exports = async ( filePath , data , options ) => {
0 commit comments