papakias papakias - 6 months ago 79
JSON Question

Reading local server .json file with mobileFirst javascript adapter

Is there any way that I can read a .json file (located in server) from a javascript http adapter?
I tried a lot of methods described in the internet but they don't seem to work because they are made for browser javascript (I get errors like XMLHttpRequest is not defined or activeObject is not defined).

for example, I used this but it doesn't work:

function readTextFile(file)
{
var rawFile = new XMLHttpRequest();
rawFile.open("GET", file, false);
rawFile.onreadystatechange = function ()
{
if(rawFile.readyState === 4)
{
if(rawFile.status === 200 || rawFile.status == 0)
{
var allText = rawFile.responseText;
return allText;
}
}
}
rawFile.send(null);
}


Is there any way that I could do this without using java?

Answer

You can read a file with Javascript as shown below.

function readFile(filename) {
    var content = "";

    var fileReader = new java.io.FileReader(filename);

    var bufferedReader = new java.io.BufferedReader(fileReader);

    var line;

    while((line = bufferedReader.readLine()) != null) {
        content += line;
    }   

    bufferedReader.close();

    return content;
}

function test() {
    var file = 'yourfilename.json';
    var fileContents;
    try {
        fileContents = readFile(file);      
    }  catch(ex) {
        // handle error                
    }

    return  {
        fileContents: fileContents
    };
}