3

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().

2 Answers 2

6

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)));
}
Sign up to request clarification or add additional context in comments.

2 Comments

Is there any alternative for the client-side? (I am trying to use this for typescript client-side) IS there any alternative?
@infamoushvher I think this is worth a separate question.
-1

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

3 Comments

where are we using glob here? it's normal file read, that I would preferably avoid.
If you don't want to modificate your code again get the paths with the glob.
path.join returns a string, with no forEach method. and the asterisk is also not working

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.