我有一些 txt
文件,其中包含一些自定义内容。文件名包含在 JSON
内。
{
txtFiles: ['./file1.txt', './file2.txt', './file3.txt']
}
我想要求
他们能够访问他们在JS
中的内容。像这样的事情:
const txtFile = require('json!abracadabra!myJsonFile.json');
console.log(txtFile[0]); // should give me a content of file1.txt, not the path
我知道我可以做一些技巧,例如创建文本变量并将其保存到 .js
文件中,然后照常 require
它。像这样:
// 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');
这是可行的,但解决方案有点棘手且丑陋。如何以更好的方式实现相同的目标?
最佳答案
使用 Node 的fs API ;特别是readFile 和/或 readFileSync
您仍然可以要求 .json
包含文本文件列表,但您应该使用 readFile
/readFileSync
来读取文本文件的内容,而不是滥用 require
。
关于javascript - 使用 JavaScript 获取 JSON 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43604539/