Home > Enterprise >  I get require is not defined error if I call it from external files
I get require is not defined error if I call it from external files

Time:01-10

Hi,

I made an app for node.js so my app.js looks like this:

global.fs = require("fs");
global.vm = require('vm');

var includefile = function(path) {
    var code = fs.readFileSync(path);
    vm.runInThisContext(code, path);
}.bind(this);

includefile("variables.js");

as for variables.js I have this:

global.app = require("express")();

but when I start the app I get this error:

require is not defined at variables.js

why is it that requires loads fine if executed from app.js but not from an external file?

Thank you.

CodePudding user response:

I'm a little confused, is variables.js just another source file in your project? All you should need to do is require the file in like you've done at the top. As an example for variables.js:

const Variables = {
   fs: "some_value"
};

module.exports = Variables;

And for app.js

const { Variables } = require("./variables.js");

const fs = Variables.fs;

Executing console.log(fs); in app.js will print "some_value". Same can be done with functions.

CodePudding user response:

If variables.js is part of your project code, you should use the answer of M. Gercz.

If it's not part of your project code and you want to get some information from it, you could use a json file:

app.js

const variables = require('variables.json');
console.log(variables.whatever);

variables.json

{ whatever: "valuable information" }

If it's not certain, that variables.json is preset, you can do a check using fs.existsSync;

Notice: As jfriend00 commented, using global is not recommended.

  •  Tags:  
  • Related