Skip to content

Commit 1f9ea2b

Browse files
committed
add overwrite option to helper.save
1 parent 4a81269 commit 1f9ea2b

File tree

3 files changed

+32
-4
lines changed

3 files changed

+32
-4
lines changed

README.md

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,11 @@
2727

2828
> Saves a file into any path
2929
30-
**rcs.helper.save(destinationPath, data, cb)**
30+
**rcs.helper.save(destinationPath, data[, options] cb)**
31+
32+
Options:
33+
34+
- overwrite (Boolean): If it should overwrite an existing file. Default `false`.
3135

3236
Example:
3337

lib/options/helper.js

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -20,15 +20,27 @@ const helper = module.exports = {};
2020
*
2121
* @return {Function} cb
2222
*/
23-
helper.save = (destinationPath, data, cb) => {
23+
helper.save = (destinationPath, data, options, cb) => {
2424
// @todo check if the filepath has an .ext
2525
// @todo check if the new filename is the same .ext
26-
// @todo do not overwrite file! use for that an flag
26+
27+
// set cb if options are not set
28+
if (typeof cb !== 'function') {
29+
cb = options;
30+
options = {};
31+
}
32+
33+
if (!options.overwrite && fs.existsSync(destinationPath)) {
34+
return cb({
35+
message: 'File exist and cannot be overwritten. Set the option overwrite to true to overwrite files.'
36+
});
37+
}
38+
2739
fs.mkdirs(path.dirname(destinationPath), (err) => {
2840
fs.writeFile(destinationPath, data, (err, data) => {
2941
if (err) return cb(err);
3042

31-
return cb(null, "Successfully wrote " + destinationPath);
43+
return cb(null, `Successfully wrote ${ destinationPath }`);
3244
});
3345
});
3446
}; // /save

test/helper.spec.js

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,18 @@ describe('helper.js', () => {
2626
});
2727
});
2828

29+
it('should not overwrite the same file', done => {
30+
const filePath = path.join(testCwd, '/../config.json');
31+
const oldFile = fs.readFileSync(filePath, 'utf8');
32+
33+
rcs.helper.save(filePath, 'test content', err => {
34+
expect(err.message).to.equal('File exist and cannot be overwritten. Set the option overwrite to true to overwrite files.');
35+
expect(fs.readFileSync(filePath, 'utf8')).to.equal(oldFile);
36+
37+
done();
38+
});
39+
});
40+
2941
it('should generatea readable json string from a json object', done => {
3042
const object = { a: 1, b:2, c:3 };
3143
const jsonString = rcs.helper.objectToJson(object);

0 commit comments

Comments
 (0)