Skip to content

Commit 9081d22

Browse files
committed
use add-filename-increment
1 parent 006fb4a commit 9081d22

File tree

1 file changed

+7
-15
lines changed

1 file changed

+7
-15
lines changed

index.js

Lines changed: 7 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
const fs = require('fs');
44
const path = require('path');
5+
const increment = require('add-filename-increment');
56

67
/**
78
* Asynchronously writes data to a file, replacing the file if it already
@@ -44,7 +45,7 @@ const write = (filepath, data, options, callback) => {
4445
}
4546

4647
const opts = { encoding: 'utf8', ...options };
47-
const destpath = opts.increment ? incrementName(filepath) : filepath;
48+
const destpath = opts.increment ? incrementName(filepath, options) : filepath;
4849
const result = { path: destpath, data };
4950

5051
if (opts.overwrite === false && exists(filepath, destpath)) {
@@ -90,7 +91,7 @@ write.sync = (filepath, data, options) => {
9091
}
9192

9293
const opts = { encoding: 'utf8', ...options };
93-
const destpath = opts.increment ? incrementName(filepath) : filepath;
94+
const destpath = opts.increment ? incrementName(filepath, options) : filepath;
9495

9596
if (opts.overwrite === false && exists(filepath, destpath)) {
9697
throw new Error('File already exists: ' + destpath);
@@ -129,7 +130,7 @@ write.stream = (filepath, options) => {
129130
}
130131

131132
const opts = { encoding: 'utf8', ...options };
132-
const destpath = opts.increment ? incrementName(filepath) : filepath;
133+
const destpath = opts.increment ? incrementName(filepath, options) : filepath;
133134

134135
if (opts.overwrite === false && exists(filepath, destpath)) {
135136
throw new Error('File already exists: ' + filepath);
@@ -143,18 +144,9 @@ write.stream = (filepath, options) => {
143144
* Increment the filename if the file already exists and enabled by the user
144145
*/
145146

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);
158150
};
159151

160152
/**

0 commit comments

Comments
 (0)