How to dynamically import data in a nodejs app?

Viewed 4177

I would like to use require in a node/express app with typescript to import a json. I tried it like this:

const url = `./data/${resource}.json`;
const data = require(url);

but I get the error Cannot find module './data/my-data.json'.

I'd like to use require instead of an import in order to create the data variable dynamically depending on the value of the resource variable.

3 Answers
const path = require('path');
const url = path.resolve(__dirname, `./data/${resource}.json`);   
const data = require(url);

The require keyword is a special keyword in nodejs. It is used to load modules, and since your json file is not a module, hence the error. Try this, this way you can dynamically load your json.

import fs from 'fs';
const file = fs.readFileSync(`./data/${resource}.json`).toString();
const data = JSON.parse(file);

There may be better ways to write this function, read mode about the fs module here.


Edit: As someone had alredy pointed out, it is actually possible to dynamicallyrequire json file. Here's how,

import path from 'path';
const uri = path.resolve(__dirname, `<path_to_json_file>`);   
const data = require(uri);

However, as a standard practice, use the fs module to load static assets to your project.

import fs from 'fs';

const file = fs.readFileSync(`./data/${resource}.json`).toString();
const data = JSON.parse(file);

Related