简体   繁体   中英

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?

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 = JSON.parse(readFile(file));     
    }  catch(ex) {
        // handle error                
    }

    return  {
        fileContents: fileContents
    };
}

For those interested in using Java.

One thing you can do is create a Javascript adapter which will use Java code. It is pretty simple to set up.

First create a Javascript adapter.

Then create a Java class under the server/lib folder. I created the class ReadJSON.java under the package com.sample.customcode .

Inside the ReadJSON.java

public class ReadJSON {
    public static String readJSON() throws IOException {
       //Open File
        File file = new File("file.txt");
        BufferedReader reader = null;
        try {
           //Create the file reader
            reader = new BufferedReader(new FileReader(file));
            String text = null;

            //read file
            while ((text = reader.readLine()) != null) {}
        } finally {
             try {
                 //Close the stream
                 reader.close();
             } 
        }
        return "the text from file";
    }
}

Inside your javascript adapter you can use Java methods like below:

function readJOSN() {
    var JSONfromServer = com.sample.customcode.ReadJSON.readJSON();
    return {
        result: JSONfromServer
    };

}

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM