0

I am very new to Node.js and I'm having a hard time wrapping my head around outputting the contents of multiple JSON files.

Inside my project folder, I have a script.js file as well as a folder with multiple JSON files (one.json, two.json, three.json, four.json).

What I'm hoping to accomplish is to display the contents of each JSON file in my console.

1 Answer 1

1
// fs and path, core modules
var fs = require("fs");
var path = require("path");

// Get directory content
fs.readdir("./", (err, fileNames) => {
    // Loop fileNames array
    fileNames.forEach(filename => {
        // Get only .json files
        if (path.extname(filename) == ".json"){
            // Read file content
            fs.readFile("./"+filename, "utf-8", (err, content) => {
                // Log file content
                console.log(content);
            });
        }
    });
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.