Created
January 10, 2024 19:17
-
-
Save educastellano/c200fbed4238993a16ed5346cc175809 to your computer and use it in GitHub Desktop.
JS to JSON
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env node | |
import fs from 'fs' | |
import path from 'path' | |
const args = process.argv.slice(2) | |
const input = args[0] | |
const objectPath = args[1] | |
if (!input) { | |
console.log('> Missing folder') | |
usage() | |
process.exit(1) | |
} | |
for (const filePath of fs.readdirSync(input)) { | |
if (filePath.endsWith('.js')) { | |
transformFile('./' + path.join(input, filePath)) | |
} | |
} | |
function transformFile (filePath) { | |
import(filePath).then((file) => { | |
const object = objectPath ? file.default[objectPath] : file.default | |
const json = JSON.stringify(object, null, 2) | |
const output = path.basename(filePath).split('.js')[0] + '.json' | |
fs.writeFileSync(`./json/${output}`, json) | |
console.log(`- JSON created: ./json/${output}`) | |
}) | |
} | |
function usage () { | |
console.log('usage: ./js-to-json.js folder [objectPath]') | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment