首页 > 解决方案 > Node.JS - 将多个 JSON 文件的内容输出到控制台

问题描述

我对 Node.js 还是很陌生,我很难集中精力输出多个 JSON 文件的内容。

在我的项目文件夹中,我有一个 script.js 文件以及一个包含多个 JSON 文件(one.json、two.json、three.json、four.json)的文件夹。

我希望完成的是在我的控制台中显示每个 JSON 文件的内容。

标签: jsonnode.jsconsole

解决方案


// 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);
            });
        }
    });
});

推荐阅读