|
1 | 1 | #!/usr/bin/env node |
2 | | -const fs = require("fs"); |
| 2 | +const fs = require('fs'); |
| 3 | +const path = require('path'); |
3 | 4 |
|
4 | | -const file = process.argv[2]; |
5 | | -if (!file) { |
6 | | - console.error("Usage: node sort-json.js <file.json>"); |
7 | | - process.exit(1); |
| 5 | +const input = process.argv[2]; |
| 6 | +if (!input) { |
| 7 | + console.error('Usage: node sort-json.js <file.json>'); |
| 8 | + process.exit(1); |
8 | 9 | } |
9 | 10 |
|
10 | | -const data = JSON.parse(fs.readFileSync(file, "utf8")); |
| 11 | +const baseDir = process.cwd(); |
| 12 | +const resolvedPath = path.resolve(baseDir, input); |
11 | 13 |
|
12 | | -const sorted = Object.keys(data) |
13 | | - .sort((a, b) => a.localeCompare(b)) |
14 | | - .reduce((acc, key) => { |
15 | | - acc[key] = data[key]; |
16 | | - return acc; |
17 | | - }, {}); |
| 14 | +if (!resolvedPath.startsWith(baseDir + path.sep) || path.extname(resolvedPath).toLowerCase() !== '.json') { |
| 15 | + console.error('Error: Invalid file path or file type.'); |
| 16 | + process.exit(1); |
| 17 | +} |
18 | 18 |
|
19 | | -fs.writeFileSync(file, JSON.stringify(sorted, null, 2) + "\n"); |
| 19 | +try { |
| 20 | + const data = JSON.parse(fs.readFileSync(resolvedPath, 'utf8')); |
| 21 | + const sorted = Object.fromEntries( |
| 22 | + Object.entries(data).sort(([keyA], [keyB]) => keyA.localeCompare(keyB)) |
| 23 | + ); |
| 24 | + fs.writeFileSync(resolvedPath, JSON.stringify(sorted, null, 2) + '\n'); |
| 25 | +} catch (err) { |
| 26 | + console.error('Error processing JSON file:', err.message); |
| 27 | + process.exit(1); |
| 28 | +} |
0 commit comments