Skip to content

Instantly share code, notes, and snippets.

@burkeholland
Last active September 30, 2022 08:12
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save burkeholland/c1119c264cec255f0d3d to your computer and use it in GitHub Desktop.
Save burkeholland/c1119c264cec255f0d3d to your computer and use it in GitHub Desktop.
Reading A Local JSON File With NativeScript

In NativeScript, the http module doesn't currently support making network requests to the local file system. That work is intended to be done by the file reader. It's pretty simple to read a local file and parse its contents as JSON.

This is the TypeScript/Promise version of what Emil Oberg created for the same question on StackOverflow. This module should be reusable for any and all asyncronous local JSON read operations.

import * as fs from 'file-system';

var documents = fs.knownFolders.currentApp();

class FileReader {
    static readJSON(path: string) {
        var jsonFile = documents.getFile(path);
        return new Promise<Object>((resolve, reject) => {
            try {
                
                jsonFile.readText().then((content: string) => {
                    let data = <Array<Object>>JSON.parse(content);
                    resolve(data);   
                });
                        
            }
            catch (err) {
                reject(err);
            }
        });
    }   
}

export default FileReader;
@NickIliev
Copy link

NickIliev commented Nov 20, 2018

With TypeScript 2.9.x and above we can now use resolveJsonModule and directly treat JSON files as modules. Sample project here.

Example

// config.json
{
    "count": 42,
    "users": [
        {"name": "John", "age": 35},
        {"name": "Ann", "age": 32},
        {"name": "George", "age": 24},
        {"name": "Mary", "age": 27},
        {"name": "Vivian", "age": 21}
    ],
    "env": "debug"
}
// your-typescript-file.ts
import config from "./config.json";

console.log(config.count); // 42
console.log(config.env); // "debug"
// tsconfig.json
{
    "compilerOptions": {
        "module": "commonjs",
        "resolveJsonModule": true,
        "esModuleInterop": true
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment