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;
move this line
let jsonFile = documents.getFile(path);
inside thelet{}
so if the JSON file doesn't exist, the thrown error is caught and returned with the Promise.Also to note, the file path always defaults to the app root, not the current file directory. :)
Personally I added this method into my own little Utility class, works a treat. Returns raw JSON data so that other functions that call this method can parse the JSON through different interfaces (so JSON data is output as a specific type of object). Here's my code: