File tree Expand file tree Collapse file tree 3 files changed +32
-4
lines changed
Expand file tree Collapse file tree 3 files changed +32
-4
lines changed Original file line number Diff line number Diff line change 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
3236Example:
3337
Original file line number Diff line number Diff 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
Original file line number Diff line number Diff 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 ) ;
You can’t perform that action at this time.
0 commit comments