【问题标题】:Import all files from a folder in VSCode Studio Code Webview API从 VSCode Studio Code Webview API 中的文件夹导入所有文件
【发布时间】:2020-01-30 13:40:12
【问题描述】:

我正在导入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"

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

【问题讨论】:

    标签: javascript json typescript visual-studio-code vscode-extensions


    【解决方案1】:

    假设您使用的是 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

    【讨论】:

    • 我在 Visual Studio 代码 webview api 中使用 Typescript。我试过 import * as fs from 'fs';让 testDataPath = "../test" 让文件名 = fs.readdirSync(testDataPath) 文件名 = 文件名.filter(it => it.endsWith(".json")) 让 runvalue = []; for(让文件名的文件名){让文件= JSON.parse(fs.readFileSync(testDataPath +“/”+文件名,“utf-8”))让json = Object.values(文件[“所有点”]) ; runvalue = [...runvalue, new Set(json)] } 但它给出错误:“Uncaught TypeError: fs.readdirSync is not a function”
    • 你是如何运行代码的?如果这是在 NodeJS 中运行的,那么它应该可以正常工作
    • 它的 Visual Studio 代码 webview api。打字稿转换为 javascript 并作为 Web 扩展运行。 code.visualstudio.com/api/extension-guides/webview
    • 对不起,我不熟悉编写 vscode 扩展 - 您应该编辑您的问题以包含此详细信息,因为它很重要
    猜你喜欢
    • 2023-04-02
    • 2015-07-10
    • 2017-04-26
    • 2019-08-25
    • 1970-01-01
    • 2016-11-04
    • 2016-10-14
    • 2015-03-12
    • 1970-01-01
    相关资源
    最近更新 更多