How to dynamically import data in a nodejs app?











up vote
0
down vote

favorite












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.










share|improve this question
























  • The most likely cause for your problem is the file path to your JSON file relative to your calling code. Can you verify and post the directory structure?
    – Paul
    7 hours ago















up vote
0
down vote

favorite












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.










share|improve this question
























  • The most likely cause for your problem is the file path to your JSON file relative to your calling code. Can you verify and post the directory structure?
    – Paul
    7 hours ago













up vote
0
down vote

favorite









up vote
0
down vote

favorite











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.










share|improve this question















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.







node.js json typescript express ejs






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited 8 hours ago









Gtm

13




13










asked 20 hours ago









Alex

185




185












  • The most likely cause for your problem is the file path to your JSON file relative to your calling code. Can you verify and post the directory structure?
    – Paul
    7 hours ago


















  • The most likely cause for your problem is the file path to your JSON file relative to your calling code. Can you verify and post the directory structure?
    – Paul
    7 hours ago
















The most likely cause for your problem is the file path to your JSON file relative to your calling code. Can you verify and post the directory structure?
– Paul
7 hours ago




The most likely cause for your problem is the file path to your JSON file relative to your calling code. Can you verify and post the directory structure?
– Paul
7 hours ago












3 Answers
3






active

oldest

votes

















up vote
0
down vote













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





share|improve this answer





















  • While this code snippet may be the solution, including an explanation really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion.
    – Tân Nguyễn
    7 hours ago


















up vote
0
down vote













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.






share|improve this answer






























    up vote
    -1
    down vote
















    import fs from 'fs';

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








    share|improve this answer























    • This answer is not only incorrect, it parrots an answer given 10 hours earlier
      – Paul
      7 hours ago











    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














     

    draft saved


    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53343722%2fhow-to-dynamically-import-data-in-a-nodejs-app%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    3 Answers
    3






    active

    oldest

    votes








    3 Answers
    3






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes








    up vote
    0
    down vote













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





    share|improve this answer





















    • While this code snippet may be the solution, including an explanation really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion.
      – Tân Nguyễn
      7 hours ago















    up vote
    0
    down vote













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





    share|improve this answer





















    • While this code snippet may be the solution, including an explanation really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion.
      – Tân Nguyễn
      7 hours ago













    up vote
    0
    down vote










    up vote
    0
    down vote









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





    share|improve this answer












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






    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered 11 hours ago









    Biplab Malakar

    33318




    33318












    • While this code snippet may be the solution, including an explanation really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion.
      – Tân Nguyễn
      7 hours ago


















    • While this code snippet may be the solution, including an explanation really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion.
      – Tân Nguyễn
      7 hours ago
















    While this code snippet may be the solution, including an explanation really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion.
    – Tân Nguyễn
    7 hours ago




    While this code snippet may be the solution, including an explanation really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion.
    – Tân Nguyễn
    7 hours ago












    up vote
    0
    down vote













    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.






    share|improve this answer



























      up vote
      0
      down vote













      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.






      share|improve this answer

























        up vote
        0
        down vote










        up vote
        0
        down vote









        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.






        share|improve this answer














        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.







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited 6 hours ago

























        answered 20 hours ago









        Nishkal Kashyap

        10716




        10716






















            up vote
            -1
            down vote
















            import fs from 'fs';

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








            share|improve this answer























            • This answer is not only incorrect, it parrots an answer given 10 hours earlier
              – Paul
              7 hours ago















            up vote
            -1
            down vote
















            import fs from 'fs';

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








            share|improve this answer























            • This answer is not only incorrect, it parrots an answer given 10 hours earlier
              – Paul
              7 hours ago













            up vote
            -1
            down vote










            up vote
            -1
            down vote












            import fs from 'fs';

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








            share|improve this answer

















            import fs from 'fs';

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








            import fs from 'fs';

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





            import fs from 'fs';

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






            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited 6 hours ago

























            answered 10 hours ago









            Gtm

            13




            13












            • This answer is not only incorrect, it parrots an answer given 10 hours earlier
              – Paul
              7 hours ago


















            • This answer is not only incorrect, it parrots an answer given 10 hours earlier
              – Paul
              7 hours ago
















            This answer is not only incorrect, it parrots an answer given 10 hours earlier
            – Paul
            7 hours ago




            This answer is not only incorrect, it parrots an answer given 10 hours earlier
            – Paul
            7 hours ago


















             

            draft saved


            draft discarded



















































             


            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53343722%2fhow-to-dynamically-import-data-in-a-nodejs-app%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            "Incorrect syntax near the keyword 'ON'. (on update cascade, on delete cascade,)

            Alcedinidae

            RAC Tourist Trophy