0

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?

2
  • What environment are you working in? Browser, or nodejs / command-line? Commented Apr 25, 2017 at 7:46
  • This is done on Node Commented Apr 25, 2017 at 7:49

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

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.