0

I am trying to get a sample json file using fs.readFile and fs.read in nodejs. This is the json test file that I am reading

{
    "HttpTestResponse":
        [
          { 
             "title":"testTitle2",
             "id": 2,
             "name":"testName3",
             "testArray":[{"testProp1":"testPropVal2","testProp2":"testPropVal_2"}]
          },
          {
            "title":"testTitle3",
            "id": 3,
            "name":"testName3",
            "testArray":[{"testProp1":"testPropVal3","testProp2":"testPropVal_3"}]
          }
        ]


}

This is the sample function (I am using typescript with nodejs for stricter typing)

getJSONFromFile(paramId) {
    let obj: HttpTestModel[];
    fs.exists(this.resolvedUrl, exists => {
      if (exists) {
        fs.readFile(this.resolvedUrl, 'utf-8', (err, data) => {
          if (err) {
            this.pino.info('error while reading the file', err);
          } else {
            this.pino.info('data', JSON.parse(data));
            // tslint:disable-next-line:one-variable-per-declaration
            // tslint:disable-next-line:prefer-const
            // tslint:disable-next-line:one-variable-per-declaration
            obj = JSON.parse(data);
            this.pino.info('plain data', data);
            this.pino.info('data in parseJSON', parseJson(data));
          }
        });
      }
    });
  }

THis is the output that I get. I am using Pino module and hence the output has some default levels and timestamps

{"level":30,"time":1550563397320,"msg":"plain data {\r\n    \"HttpTestResponse\":\r\n        [\r\n
{ \r\n             \"title\":\"testTitle2\",\r\n             \"id\": 2,\r\n             \"name\":\"testName3\",\r\n             \"testArray\":[{\"testProp1\":\"testPropVal2\",\"testProp2\":\"testPropVal_2\"}]\r\n
      },\r\n          {\r\n            \"title\":\"testTitle3\",\r\n            \"id\": 3,\r\n            \"name\":\"testName3\",\r\n            \"testArray\":[{\"testProp1\":\"testPropVal3\",\"testProp2\":\"testPropVal_3\"}]\r\n          }\r\n        ]\r\n        \r\n    \r\n}","pid":21212,"hostname":"INDV072294","v":1}


{"level":30,"time":1550563397321,"msg":"stringifed data {\r\n    \"HttpTestResponse\":\r\n        [\r\n
     { \r\n             \"title\":\"testTitle2\",\r\n             \"id\": 2,\r\n             \"name\":\"testName3\",\r\n             \"testArray\":[{\"testProp1\":\"testPropVal2\",\"testProp2\":\"testPropVal_2\"}]\r\n          },\r\n          {\r\n            \"title\":\"testTitle3\",\r\n            \"id\": 3,\r\n
   \"name\":\"testName3\",\r\n            \"testArray\":[{\"testProp1\":\"testPropVal3\",\"testProp2\":\"testPropVal_3\"}]\r\n          }\r\n        ]\r\n        \r\n    \r\n}","pid":21212,"hostname":"INDV072294","v":1}


{"level":30,"time":1550563397322,"msg":"data in parseJSON {\"HttpTestResponse\":[{\"title\":\"testTitle2\",\"id\":2,\"name\":\"testName3\",\"testArray\":[{\"testProp1\":\"testPropVal2\",\"testProp2\":\"testPropVal_2\"}]},{\"title\":\"testTitle3\",\"id\":3,\"name\":\"testName3\",\"testArray\":[{\"testProp1\":\"testPropVal3\",\"testProp2\":\"testPropVal_3\"}]}]}","pid":21212,"hostname":"INDV072294","v":1}

I also tried to use the parse-json module but nothing is helpming me out with the output that I want. I would want the JSON object as output and not the string, so I could store that and iterate it and filter out the desired results

Could someone help me out on this?

2 Answers 2

1

You can use pino-pretty which is a pino's plugin or a module.

npm i -S pino pino-pretty

example code like this:

const pino = require('pino')
const logger = pino({
    prettyPrint: {
        levelFirst: true,
    },
})
const filePath = '' // 

fs.exists(filePath, exists => {
    if (exists) {
        fs.readFile(filePath, 'utf-8', (err, data) => {
            if (err) {
            } else {
                const obj = JSON.parse(data);
                logger.info('data', JSON.parse(data));
                logger.info(JSON.parse(data));
                logger.info(data);
            }
        });
    }
});

logger output

INFO  [1550565533231] (19285 on aa-pc): data {"HttpTestResponse":[{"title":"testTitle2","id":2,"name":"testName3","testArray":[{"testProp1":"testPropVal2","testProp2":"testPropVal_2"}]},{"title":"testTitle3","id":3,"name":"testName3","testArray":[{"testProp1":"testPropVal3","testProp2":"testPropVal_3"}]}]}


INFO  [1550565533233] (19285 on aa-pc):
    HttpTestResponse: [
      {
        "title": "testTitle2",
        "id": 2,
        "name": "testName3",
        "testArray": [
          {
            "testProp1": "testPropVal2",
            "testProp2": "testPropVal_2"
          }
        ]
      },
      {
        "title": "testTitle3",
        "id": 3,
        "name": "testName3",
        "testArray": [
          {
            "testProp1": "testPropVal3",
            "testProp2": "testPropVal_3"
          }
        ]
      }
    ]

INFO  [1550565533234] (19285 on aa-pc): {
"HttpTestResponse":
[
{
"title":"testTitle2",
"id": 2,
"name":"testName3",
"testArray":[{"testProp1":"testPropVal2","testProp2":"testPropVal_2"}]
},
{
"title":"testTitle3",
"id": 3,
"name":"testName3",
"testArray":[{"testProp1":"testPropVal3","testProp2":"testPropVal_3"}]
}
]

}


you can try it by youself. hahaha

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you. Let me try that out and let you know. I tried with fs.readFileSync and it prints out the desired data as JSON but I wanted it to be using the async mode.
Awesome it worked. I guess I will add a few steps for those who wanted to use typescript below. Thank you so much!!
@Joey587 hahaha~ Work is fine
0

The above answer works perfectly for users using js. If you intent on using ts, then a slight modification and best practise to follow is.

First install the types (the class type definition for pino).

npm install -S @types/pino

Then install the pino pretty as above

Now create a seperate file called logger.ts and export the prertyprint configuration of pino like this

import * as pino from 'pino';

export const logger = pino({
  name: 'prj-sample',
  prettyPrint: {
    levelFirst: true,
  },
});

Now you can import the logger const anywhere in your code like this and use it

import { logger } from './../../../shared/utils/logger';
.....
.....
.....
getJSONFromFile(paramId) {
    let obj;
    fs.exists(this.resolvedUrl, exists => {
      if (exists) {
        fs.readFile(this.resolvedUrl, 'utf-8', (err, data) => {
          if (err) {
            logger.info('error while reading the file', err);
          } else {
            obj = JSON.parse(data);
            logger.info('data data :', obj.HttpTestResponse);
            logger.info('data is', JSON.parse(data));
            logger.info(JSON.parse(data));
            logger.info(data);
          }
        });
      }
    });
  }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.