简体   繁体   English

读取动态更新文件夹中包含的所有 JSON 文件

[英]Read all JSON files contained in a dynamically updated folder

I've got multiple json files contained within a directory that will dynamically be updated by users.我在一个目录中包含多个 json 文件,这些文件将由用户动态更新。 The users can add categories which will create new json files in that directory, and they can also remove categories which would delete json files in that directory.用户可以添加将在该目录中创建新的 json 文件的类别,他们还可以删除将删除该目录中的 json 文件的类别。 I'm looking for a method to read all json files contained in that folder directory, and push all the json files into a single object array.我正在寻找一种方法来读取该文件夹目录中包含的所有 json 文件,并将所有 json 文件推送到单个 object 数组中。 I imagine asynchronously would be desirable too.我想异步也是可取的。

I'm very new to using fs.我对使用 fs 很陌生。 I've management to read single json files by directory using我已经管理使用目录读取单个 json 文件

const fs = require('fs');

let data = fs.readFileSync('./sw_lbi/categories/category1.json');
let categories = JSON.parse(data);
console.log(categories);

But of course this will only solve the synchronous issue when using require()但是当然这只会解决使用require()时的同步问题

As I'll have no idea what json files will be contained in the directory because the users will also name them, I'll need a way to read all the json files by simply calling the folder directory which contains them.由于我不知道目录中将包含哪些 json 文件,因为用户也会命名它们,因此我需要一种方法来读取所有 json 文件,只需调用包含它们的文件夹目录即可。

I'm imagining something like this (which obviously is foolish)我在想象这样的事情(这显然是愚蠢的)

const fs = require('fs');

let data = fs.readFileSync('./sw_lbi/categories');
let categories = JSON.parse(data);
console.log(categories);

What would be the best approach to achieve this?实现这一目标的最佳方法是什么?

Thanks in advance.提前致谢。

First of all you need to scan this directory for files, next you need to filter them and select only JSONs, and at the end just read every file and do what you need to do首先,您需要扫描此目录中的文件,接下来您需要过滤它们和 select 仅 JSON,最后只需读取每个文件并做您需要做的事情

const fs = require('fs');
const path = require('path')

const jsonsInDir = fs.readdirSync('./sw_lbi/categories').filter(file => path.extname(file) === '.json');

jsonsInDir.forEach(file => {
  const fileData = fs.readFileSync(path.join('./sw_lbi/categories', file));
  const json = JSON.parse(fileData.toString());
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM