@@ -10,6 +10,8 @@ const isPlainObj = require('is-plain-obj');
10
10
11
11
const readFile = promisify ( fs . readFile ) ;
12
12
13
+ const hasTrailingNewline = file => / \n $ / . test ( file ) ;
14
+
13
15
const init = ( fn , filePath , data , options ) => {
14
16
if ( ! filePath ) {
15
17
throw new TypeError ( 'Expected a filepath' ) ;
@@ -37,40 +39,48 @@ const init = (fn, filePath, data, options) => {
37
39
38
40
const main = async ( filePath , data , options ) => {
39
41
let { indent} = options ;
42
+ let trailingNewline = '\n' ;
43
+ try {
44
+ const file = await readFile ( filePath , 'utf8' ) ;
45
+ if ( ! hasTrailingNewline ( file ) ) {
46
+ trailingNewline = '' ;
47
+ }
40
48
41
- if ( options . detectIndent ) {
42
- try {
43
- const file = await readFile ( filePath , 'utf8' ) ;
49
+ if ( options . detectIndent ) {
44
50
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 ;
49
55
}
50
56
}
51
57
52
58
const json = JSON . stringify ( data , options . replacer , indent ) ;
53
59
54
- return writeFileAtomic ( filePath , `${ json } \n ` , { mode : options . mode } ) ;
60
+ return writeFileAtomic ( filePath , `${ json } ${ trailingNewline } ` , { mode : options . mode } ) ;
55
61
} ;
56
62
57
63
const mainSync = ( filePath , data , options ) => {
58
64
let { indent} = options ;
65
+ let trailingNewline = '\n' ;
66
+ try {
67
+ const file = fs . readFileSync ( filePath , 'utf8' ) ;
68
+ if ( ! hasTrailingNewline ( file ) ) {
69
+ trailingNewline = '' ;
70
+ }
59
71
60
- if ( options . detectIndent ) {
61
- try {
62
- const file = fs . readFileSync ( filePath , 'utf8' ) ;
72
+ if ( options . detectIndent ) {
63
73
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 ;
68
78
}
69
79
}
70
80
71
81
const json = JSON . stringify ( data , options . replacer , indent ) ;
72
82
73
- return writeFileAtomic . sync ( filePath , `${ json } \n ` , { mode : options . mode } ) ;
83
+ return writeFileAtomic . sync ( filePath , `${ json } ${ trailingNewline } ` , { mode : options . mode } ) ;
74
84
} ;
75
85
76
86
module . exports = async ( filePath , data , options ) => {
0 commit comments