Abhi Nandan
Abhi Nandan

Reputation: 195

Read multiple json files into an array of objects in JavaScript

I have multiple json files under a folder that I need to read. The data file path is like:

./data/json1.json
./data/json2.json

My initializer class works as below:

const j1 = require('./data/json1.json');
const j2 = require('./data/json2.json');
init(){
    return j1.concat(j2);
}

Is there a better way to do this as the list of files under data could increase and every time this would require modifications?

I would preferably avoid a solution with looping in the folder and read file to append in an array object in init().

Upvotes: 3

Views: 7481

Answers (2)

sveyda
sveyda

Reputation: 76

You can use glob package.

const glob = require("glob");
const path = require("path");

glob('data/*.json', function (er, files) {
  files.forEach(function(file) {
    //Do your thing
  })
})

Upvotes: -1

vsemozhebuty
vsemozhebuty

Reputation: 13782

As a variant:

'use strict';

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

const dir = './data';

function init() {
  return fs.readdirSync(dir)
           .filter(name => path.extname(name) === '.json')
           .map(name => require(path.join(dir, name)));
}

Upvotes: 5

Related Questions