Q:

Require files from JSON using JavaScript

I have some txt files with some custom content inside. File names are contained inside JSON.
{
   txtFiles: ['./file1.txt', './file2.txt', './file3.txt']
}

I want to require them to have an access to their content in JS. Something like this:
const txtFile = require('json!abracadabra!myJsonFile.json');
console.log(txtFile[0]); // should give me a content of file1.txt, not the path

I know I could do some tricks like creating text variable and save it into .js file and then require it as usual. Like this:
// 1. create string variable
const myStringVar = `module.exports = [\'require(\'raw!./file1.txt\')\', ...];`;
// 2. then save this into myTxtFiles.js
// 3. then require the file
const txtFileContents = require('./myTxtFiles.js');

This is working, but the solution is kinda tricky and ugly. How to achieve the same in some better way?

A:

Use node's fs API; in particular, readFile
 and/or readFileSync
You can still require your .json containing the list of text files, but you should use readFile / readFileSync to read the contents of the text files rather than abusing require.

