How to use 'require' to import a JSON in NestJS controller?

12,124
  1. I guess the problem lies in the way you import your .json file (change import instead of const)
  2. Another advice or solution would be to leverage the .json() method of the res object (which is actually the express adapter response object).

Let's try with this code:

Your common.controller.ts file:

import { Controller, Get, Res, HttpStatus, Query } from '@nestjs/common';
import { Response } from 'express';

import * as MOCKED_RESPONSE_TS from './data/payment-method.data'; // this ts file should still be imported fine
import * as MOCKED_RESPONSE from './data/payment-method-mock.json'; // or use const inside the controller function

@Controller('commons')
export class CommonController {

@Get('/payment-method')
  getPaymentMoethod(@Res() res: Response): any {
    res.status(HttpStatus.OK).json(MOCKED_RESPONSE); // <= this sends response data as json
  }
}

Also in your tsconfig.json file, don't forget to add this line:

tsconfig.json

{
  "compilerOptions": {
    // ... other options 

    "resolveJsonModule": true, // here is the important line, this will help VSCode to autocomplete and suggest quick-fixes

    // ... other options
}

Last thoughts: you could use the sendfile() method of the res object depending on whether you want to send back a json file or the content of your json file.

Let me know if it helps ;)

Share:
12,124
Daniel Delgado
Author by

Daniel Delgado

Hello, I am a tech enthusiast and a full stack engineer living in Peru.

Updated on June 14, 2022

Comments

  • Daniel Delgado
    Daniel Delgado almost 2 years

    I'm trying to return a json file as a controller response, but I can't get the content of the json.

    import { Controller, Get, Res, HttpStatus, Query } from '@nestjs/common';
    import { Response } from 'express';
    
    import * as MOCKED_RESPONSE_TS from './data/payment-method.data'; // this ts file is imported fine
    const MOCKED_RESPONSE = require('./data/payment-method-mock'); // this json file is not found
    
    @Controller('commons')
    export class CommonController {
    
    @Get('/payment-method')
      getPaymentMoethod(@Res() res: Response): any {
        res.status(HttpStatus.OK).send(MOCKED_RESPONSE);
      }
    
    }
    

    Actually the log returns: Error: Cannot find module './data/payment-method' and the app doesn't compile

    I have done this with express (even with typescript) and works fine.

    I don't know if i have to setup my project to read jsons (I'm newby on nest). By the moment I have created a typescript file exporting a const with the json content and I called it successfuly