How to dynamically import data in a nodejs app?





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







0















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
    Nov 17 '18 at 7:49


















0















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
    Nov 17 '18 at 7:49














0












0








0








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 Nov 17 '18 at 6:35









Gtm

15




15










asked Nov 16 '18 at 18:47









AlexAlex

205




205













  • 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
    Nov 17 '18 at 7:49



















  • 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
    Nov 17 '18 at 7:49

















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
Nov 17 '18 at 7:49





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
Nov 17 '18 at 7:49












3 Answers
3






active

oldest

votes


















0














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.

    – Foo
    Nov 17 '18 at 7:45



















1














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

































    -1

















    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
      Nov 17 '18 at 7:47












    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',
    autoActivateHeartbeat: false,
    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









    0














    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.

      – Foo
      Nov 17 '18 at 7:45
















    0














    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.

      – Foo
      Nov 17 '18 at 7:45














    0












    0








    0







    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 Nov 17 '18 at 3:35









    Biplab MalakarBiplab Malakar

    43748




    43748













    • 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.

      – Foo
      Nov 17 '18 at 7:45



















    • 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.

      – Foo
      Nov 17 '18 at 7:45

















    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.

    – Foo
    Nov 17 '18 at 7:45





    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.

    – Foo
    Nov 17 '18 at 7:45













    1














    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






























      1














      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




























        1












        1








        1







        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 Nov 17 '18 at 8:40

























        answered Nov 16 '18 at 19:06









        Nishkal KashyapNishkal Kashyap

        397311




        397311























            -1

















            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
              Nov 17 '18 at 7:47
















            -1

















            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
              Nov 17 '18 at 7:47














            -1












            -1








            -1










            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 Nov 17 '18 at 8:40

























            answered Nov 17 '18 at 4:51









            GtmGtm

            15




            15













            • This answer is not only incorrect, it parrots an answer given 10 hours earlier

              – Paul
              Nov 17 '18 at 7:47



















            • This answer is not only incorrect, it parrots an answer given 10 hours earlier

              – Paul
              Nov 17 '18 at 7:47

















            This answer is not only incorrect, it parrots an answer given 10 hours earlier

            – Paul
            Nov 17 '18 at 7:47





            This answer is not only incorrect, it parrots an answer given 10 hours earlier

            – Paul
            Nov 17 '18 at 7:47


















            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            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

            Xamarin.iOS Cant Deploy on Iphone

            Glorious Revolution

            Dulmage-Mendelsohn matrix decomposition in Python