javascript - 使用 JavaScript 获取 JSON 文件

标签 javascript json node.js

我有一些 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/

相关文章:

php - jQuery 验证 PHP 响应

c# - 将 JSON 反序列化为可读格式

json - 读/写本地 json 文件 swift 4

javascript - 我如何使用外部 routes.js 以便我不必在 app.js 中定义我的路线?

json - 有没有办法自动将 package.json 的最新或星号(*)标记更改为特定版本?

php - 如何将 id 与主干中的表行删除按钮关联

javascript - 如果变量等于 False,则通过 JavaScript 重定向?

node.js - 为什么连接到集群在 IoRedis 中不断循环?

javascript - 从 'click' 事件处理程序返回特定的 DOM 元素

Javascript - 卸载/页面隐藏事件中的 AJAX 调用