67 lines
1.4 KiB
JavaScript
Raw Normal View History

2016-03-18 11:12:50 +01:00
'use strict';
/**
* Module dependencies
*/
// Node.js core.
const path = require('path');
// Public node modules.
const _ = require('lodash');
const fs = require('fs-extra');
const reportback = require('reportback')();
/**
* Generate a JSON file
*/
2018-05-04 17:36:50 +02:00
/* eslint-disable prefer-template */
2021-04-29 11:11:46 +02:00
module.exports = function(options, handlers) {
2016-03-18 11:12:50 +01:00
// Provide default values for handlers.
handlers = reportback.extend(handlers, {
2021-04-29 11:11:46 +02:00
alreadyExists: 'error',
2016-03-18 11:12:50 +01:00
});
// Provide defaults and validate required options.
_.defaults(options, {
2021-04-29 11:11:46 +02:00
force: false,
2016-03-18 11:12:50 +01:00
});
2021-04-29 11:11:46 +02:00
const missingOpts = _.difference(['rootPath', 'data'], Object.keys(options));
2016-03-18 11:12:50 +01:00
if (missingOpts.length) {
return handlers.invalid(missingOpts);
}
const rootPath = path.resolve(process.cwd(), options.rootPath);
// Only override an existing file if `options.force` is true.
fs.exists(rootPath, exists => {
2016-03-18 11:12:50 +01:00
if (exists && !options.force) {
return handlers.alreadyExists('Something else already exists at `' + rootPath + '`.');
}
if (exists) {
fs.remove(rootPath, err => {
2016-03-18 11:12:50 +01:00
if (err) {
return handlers.error(err);
}
_afterwards_();
});
} else {
_afterwards_();
}
function _afterwards_() {
2021-04-29 11:11:46 +02:00
fs.outputJSON(rootPath, options.data, { spaces: 2 }, err => {
2016-03-18 11:12:50 +01:00
if (err) {
return handlers.error(err);
} else {
handlers.success();
}
});
}
});
};