繁体   English   中英

从 VSCode Studio Code Webview API 中的文件夹导入所有文件

[英]Import all files from a folder in VSCode Studio Code Webview API

我正在导入 json 文件如下:

import input1 = require("../test/test1.json");
import input2 = require("../test/test2.json");
import input3 = require("../test/test3.json");
import input4 = require("../test/test4.json");
import input5 = require("../test/test5.json");

我的 tsconfig 设置是:

"module": "commonjs",
"target": "es6",

但是我需要导入包含大量 json 文件的整个“test”文件夹。 如何导入所有文件并将每个文件分配给“输入”变量?

更新:

我已经尝试了@Michael 建议的以下代码。 但是给出了以下错误。

const fs = require('fs');

let testDataPath = "../test"
let filenames = fs.readdirSync(testDataPath)

filenames = filenames.filter(it => it.endsWith(".json"))
let runvalue = [];
for(let filename of filenames) {
   let file = JSON.parse(fs.readFileSync(testDataPath + "/" + filename, "utf-8"))
   let json = Object.values(file["covered-points"]);
    runvalue = [...runvalue, new Set(json)]
}

但它给出错误: "Uncaught TypeError: fs.readdirSync is not a function"错误: "Uncaught TypeError: fs.readdirSync is not a function"

我无法弄清楚 Visual Studio 代码中的“fs”有什么问题。 有人请帮助我。 感谢您的时间。

假设您使用的是 NodeJS 而不是 Web 浏览器,最好的方法是使用fs核心模块读取目录内容,然后读取文件内容。 例如:

let testDataPath = "./test"
let filenames = fs.readdirSync(testDataPath)
filenames = filenames.filter(it => it.endsWith(".json"))

for(let filename of filenames) {
   let json = JSON.parse(fs.readFileSync(testDataPath + "/" + filename, "utf-8"))
   //do something with the json
}

笔记:

  • 通常,您应该使用这些函数的异步版本,但我会将其作为练习留给您
  • 给定的路径需要相对于程序的当前工作目录,而不是调用函数的文件

参考: https : //nodejs.org/api/fs.html

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM