javascript - How to load the data from .json file in httplistener -


i'm new on webservice/javascript development environment. got task - current our httplistener code serves localhost request .js file. need capable of putting json objects around in httplistener.

  • receiving value types, objects , list (or array) json file (.json) , converts json string javascript object
  • sending value types, objects , list javascript
  • outputting above json data console

it great if can share ideas/solution how implement on this.

here's our code works .js - httplistener.cs:

private static void main() { var server = new httplistener(); server.prefixes.add("http://localhost:80/");  server.start(); console.writeline("listening...");  while (true) {    httplistenercontext context = server.getcontext();    httplistenerresponse response = context.response;     string fileid = string.empty;    try    {    string page = path.combine(directory.getcurrentdirectory(), context.request.url.localpath.replace("/", @"\").substring(1));     console.writeline("get request {0}", page);      if (!string.isnullorempty(page) && !page.endswith(".js"))     {         console.writeline("file not .js file.");         continue;     }        // check requested file exists        // file id property query string.       fileid = context.request.querystring["fileid"];        string msg;       using (var sr = new streamreader(page))       {            msg = sr.readtoend();       }        byte[] buffer = encoding.utf8.getbytes(msg);       response.contentlength64 = buffer.length;       response.contenttype = "text/javascript";        using (stream st = response.outputstream)       {            console.writeline(buffer.length);            st.write(buffer, 0, buffer.length);            context.response.statuscode = (int)httpstatuscode.ok;            context.response.statusdescription = "ok";            console.writeline("request done:{0}", fileid);       }       catch { } // suppress exceptions             {            context.response.close();            console.writeline("response closed:{0}", fileid);       } } 

}

example of data.json. don't know field name , data type coming.

[   {     "name": "george",     "gender": "male",     "age": "5 years"   },   {     "name": "nancy",     "gender": "female",     "age": "10 years"   },   {     "name": "alex",     "gender": "male",     "age": "3 years"   },   {     "name": "maximus",     "gender": "male",     "age": "7 years"   }  ] 


Comments

Popular posts from this blog

commonjs - How to write a typescript definition file for a node module that exports a function? -

openid - Okta: Failed to get authorization code through API call -

thorough guide for profiling racket code -