Reputation: 373
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
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:
ref: https://nodejs.org/api/fs.html
Upvotes: 1