2
2
3
3
const fs = require ( 'fs' ) ;
4
4
const path = require ( 'path' ) ;
5
+ const increment = require ( 'add-filename-increment' ) ;
5
6
6
7
/**
7
8
* Asynchronously writes data to a file, replacing the file if it already
@@ -44,7 +45,7 @@ const write = (filepath, data, options, callback) => {
44
45
}
45
46
46
47
const opts = { encoding : 'utf8' , ...options } ;
47
- const destpath = opts . increment ? incrementName ( filepath ) : filepath ;
48
+ const destpath = opts . increment ? incrementName ( filepath , options ) : filepath ;
48
49
const result = { path : destpath , data } ;
49
50
50
51
if ( opts . overwrite === false && exists ( filepath , destpath ) ) {
@@ -90,7 +91,7 @@ write.sync = (filepath, data, options) => {
90
91
}
91
92
92
93
const opts = { encoding : 'utf8' , ...options } ;
93
- const destpath = opts . increment ? incrementName ( filepath ) : filepath ;
94
+ const destpath = opts . increment ? incrementName ( filepath , options ) : filepath ;
94
95
95
96
if ( opts . overwrite === false && exists ( filepath , destpath ) ) {
96
97
throw new Error ( 'File already exists: ' + destpath ) ;
@@ -129,7 +130,7 @@ write.stream = (filepath, options) => {
129
130
}
130
131
131
132
const opts = { encoding : 'utf8' , ...options } ;
132
- const destpath = opts . increment ? incrementName ( filepath ) : filepath ;
133
+ const destpath = opts . increment ? incrementName ( filepath , options ) : filepath ;
133
134
134
135
if ( opts . overwrite === false && exists ( filepath , destpath ) ) {
135
136
throw new Error ( 'File already exists: ' + filepath ) ;
@@ -143,18 +144,9 @@ write.stream = (filepath, options) => {
143
144
* Increment the filename if the file already exists and enabled by the user
144
145
*/
145
146
146
- const incrementName = destpath => {
147
- let file = { ...path . parse ( destpath ) , path : destpath } ;
148
- let name = file . name ;
149
- let prev ;
150
- let n = 1 ;
151
-
152
- while ( prev !== file . path && fs . existsSync ( file . path ) ) {
153
- prev = file . path ;
154
- file . path = path . resolve ( file . dir , `${ name } (${ ++ n } )${ file . ext } ` ) ;
155
- }
156
-
157
- return file . path ;
147
+ const incrementName = ( destpath , options = { } ) => {
148
+ if ( options . increment === true ) options . increment = void 0 ;
149
+ return increment ( destpath , options ) ;
158
150
} ;
159
151
160
152
/**
0 commit comments