json - Node.JS - 将多个 JSON 文件的内容输出到控制台
问题描述
我对 Node.js 还是很陌生,我很难集中精力输出多个 JSON 文件的内容。
在我的项目文件夹中,我有一个 script.js 文件以及一个包含多个 JSON 文件(one.json、two.json、three.json、four.json)的文件夹。
我希望完成的是在我的控制台中显示每个 JSON 文件的内容。
解决方案
// 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);
});
}
});
});
推荐阅读
- javascript - 等价于 image/png;base64 用于 excel 文件流
- reactjs - 如何使用 Spring MVC 和 React 作为前端服务器?
- visual-c++ - VS 编译器是否提供了一个宏变量来判断浮点模型是否精确?
- sql - 使用循环的sql过程打印错误结果
- dialogflow-es - agent.add(conv) 在 dialogflow-fulfillment-library 中不起作用?
- swift - 为什么这个函数没有返回任何东西?
- php - 如何在同一页面中使用 html 和 php 在下拉的选择更改事件的输入字段中从数据库中获取选定的数据
- arrays - 使用 mongodb 的 java 驱动程序从集合中获取数组字段
- c# - .Net Core 2 OpenID Connect 身份验证和多个身份
- google-cloud-platform - Apache Beam python sdk 因 IllegalArgumentException 而失败