JSON Formatter
Read a JSON file and print clean formatted output.
5 upvotes
10 upvotes
JSON Formatter
You are required to build a CLI tool using Node.js that reads a JSON file and prints formatted JSON to the terminal.
The tool should accept a JSON file path from the terminal. If the user does not pass a file path, it should print a friendly error.
Create a file called user.json with this content:
Create another file called broken.json with this content:
This file is missing the final }. Keep it broken so you can test the error path.
Here are some example commands you can run to test your CLI:
On successful execution, the output should look like this:
If the file contains invalid JSON, print a friendly error:
If the file cannot be read, print this error:
If the user does not pass a file path, print this error:
Errors should go to stderr, and the command should set a non-zero exit code.
The goal of this project is to practice reading files, parsing JSON, handling invalid data, and printing clean output that another command could redirect into a file.
You will need these Node.js APIs:
process.argvto read the file path from the terminal.node:fs/promisesto read the file contents.JSON.parse()to turn JSON text into a JavaScript value.JSON.stringify()to print formatted JSON.
Solution
Solution:
