1

I am working on a project with node.js, where there are multiple JSON files in a folder say FILES and I have to access contents of the files. One approach is to use

var a = require('jsonfile')

And then perform the required queries.

But suppose if I have around 20 files, it would be a headache to write them all with the require function, is there a better way to do this. I know Mongodb can be used in this case, but I want to be to use JSON files. Is there a better way to solve this problem?

Neil Lunn
  • 148,042
  • 36
  • 346
  • 317
pkoli
  • 646
  • 8
  • 21

2 Answers2

2

You can do something like this:

var data = {},
    dir = __dirname + '/FILES/';
fs.readdirSync(dir).forEach(function (file) {
    data[file.replace(/\.json$/, '')] = require(dir + file);
});

Then for example you can access a json file named config.json with data.config.

You can also use require-dir module like this to do the same:

var requireDir = require('require-dir');
var data = requireDir(__dirname + '/FILES/');
Farid Nouri Neshat
  • 29,438
  • 6
  • 74
  • 115
  • Getting an error on this line says unexpected token on the '.' before the forEach. fs.readdirSync(dir).forEach(function (file) { – pkoli Mar 16 '15 at 16:21
  • @pkoli I doubt the fact you are running the same code as above. I can't reproduce the error you mentioned. – Farid Nouri Neshat Mar 20 '15 at 10:12
0

Couldn't you just use something like this?

How do you get a list of the names of all files present in a directory in Node.js?

Write all the filenames in an array and then loop over it.

Or you could write an index-file with all the current files and read that first.

Community
  • 1
  • 1
rst
  • 2,510
  • 4
  • 21
  • 47