Search code examples
javascriptnode.jsrequire

Did node require change?


I previously included other js files into my node projects using require as seen on this post. But for some reason this no longer works, did Node change or am I missing some mistake?

This is my code:

main.js:

require("./test");

console.log(x);

test.js:

var x = 3;

Running this code results in this error message:

main.js:3
console.log(x);
            ^

ReferenceError: x is not defined

Solution

  • Looking at an other project I found what I wanted:

    test.js:

    global.x = 3;
    

    main.js:

    require("./test");
    
    console.log(x);