Skip to content

Instantly share code, notes, and snippets.

@jehy
Created May 27, 2020 15:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jehy/47b9458e23f508b80da39219a1d409d6 to your computer and use it in GitHub Desktop.
Save jehy/47b9458e23f508b80da39219a1d409d6 to your computer and use it in GitHub Desktop.
move test data from js file to json
'use strict';
// TODO small and primitive values should not be put to separate files
const fs = require('fs');
const path = require('path');
const args = process.argv;
console.log('args', args);
const file = args[2];
console.log('file', file);
const data = require(file);
const keys = Object.keys(data);
console.log('exporting keys', keys);
const newPath = path.join(path.dirname(file), 'objects');
console.log('using path', newPath);
if (!fs.existsSync(newPath))
{
fs.mkdirSync(newPath);
}
const indexExports = {};
Object.entries(data).forEach(([key, value])=>{
const newFilePath = path.join(newPath, `${key}.json`);
console.log(`making ${newFilePath}`);
indexExports[key] = (`./objects/${key}.json`);
fs.writeFileSync(newFilePath, JSON.stringify(value, null, 3), 'utf8');
})
const indexExportsData = Object.entries(indexExports).map(([key, value])=>{
return `\t${key}`;
}).join(',\n');
const indexVariables = Object.entries(indexExports).map(([key, value])=>{
return `const ${key} = fs.readJsonSync(path.join(__dirname, '${value}'));`;
}).join('\n');
const indexFile = `'use strict';\n\nconst fs = require('fs-extra');\nconst path = require('path');\n\n${indexVariables}\n\nmodule.exports = {\n${indexExportsData}\n};`;
const newFilePath = path.join(path.dirname(file), `${path.basename(file)}.fixed.js`);
fs.writeFileSync(newFilePath, indexFile, 'utf8');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment