Nihar
Nihar

Reputation: 373

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

I am importing json files as following:

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");

My tsconfig settings is:

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

But I need to import the whole "test" folder with a lot of json files. How can I import all the files and assign each file to a "input" variable?

Update:

I have tried the following code that was suggested by @Michael. But is gives following error.

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)]
}

But its giving error: "Uncaught TypeError: fs.readdirSync is not a function"

I can't figure out whats wrong with "fs" in visual studio code. Someone please help me. Thank you for your time.

Upvotes: 1

Views: 2029

Answers (1)

Michael
Michael

Reputation: 2454

Assuming that you are in NodeJS rather than in a web browser, the best way would be to use the fs core module to read the directory contents, and then the file contents. Eg:

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
}

Note:

  • In general you should use the asynchronous versions of these functions, but I'll leave that as an exercise for you to do
  • The path given needs to be relative to the current working directory of the program, rather than the file the function is called in

ref: https://nodejs.org/api/fs.html

Upvotes: 1

Related Questions