Skip to content

Instantly share code, notes, and snippets.

@educastellano
Created January 10, 2024 19:17
Show Gist options
  • Save educastellano/c200fbed4238993a16ed5346cc175809 to your computer and use it in GitHub Desktop.
Save educastellano/c200fbed4238993a16ed5346cc175809 to your computer and use it in GitHub Desktop.
JS to JSON
#!/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