'TypeScript - Loading JSON objects from a directory

I'm relatively new to TypeScript and I am facing a problem.

I have to dynamically load objects from a directory which contains a number of JSON files. File names are generated by an export bash script that populates a resource directory. I can scroll through the file names, and I'd like to load the objects from a function, such as:

/**
 * Reads resources from file (JSON format) and add them to the specified mapEntry
 * @param mapEntry Map entry of Map<Accounts, Resource[]>()
 * @param file Resource file name 
 * @returns Merged mapEntry with new resource read from the file
 */
function addResources(mapEntry: Resource[], file: any): Resource[] {
    // TODO: load resource object from JSON file
    return mapEntry;
}

I have not found any possible solution, unless I dynamically generate and include typescript files from an external script.

Any help would be greatly appreciated. Giacomo



Solution 1:[1]

I managed to read the files and load them into a JSON object:

/**
 * Reads resources from file (JSON format) and add them to the specified mapEntry
 * @param mapEntry Map entry of Map<Accounts, Resource[]>()
 * @param file File name
 * @returns Merged mapEntry with new resource read from the file
 */
function addResources(mapEntry: Resource[], file: any): Resource[] {
    let resources: Resource[] = new Array<Resource>();

    const fs = require('fs');
    fs.readFile(file, function(err: any, data: any) {
        if (err) {
            console.log(err);
        } else {
                const resourceJson = JSON.parse(data.toString());
                // Reading JSON properties
        }
    });

    return mapEntry;
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 giacomello