Is it possible to import Javascript variables (Node.js)?

Asked

Viewed 1,894 times

5

I have variables in app.js:

var G = {};
module.exports = G;

var DATA = G.DATA = 'DATA';
var F1 = G.F1 = function(val)
{
  return val;
};

This way I can export variables under the object G, and at the same time you can access the type variable directly DATA without G. prefix.

Now, I want to audition for app.js in test.js

var G = require('./app.js');
console.log(G.DATA);  // -> DATA

This works, but I also want to access the writing variable directly DATA without G. Prefix as console.log(DATA); // -> DATA

Surely, I could do as:

var DATA = G.DATA;

For each (property) export variable and module required G object, but obviously it is a tedious process to add each variable to the test file manually to match the G object.

Is there any way to do this automatically?

So far, I’ve been pessimistic since

JS function closes var in the scope itself, so in theory, there is no way to have an auxiliary function to var for each property object.

I’d like to avoid any eval or VM knot solution. I tried them in the past, and had too many problems.

3 answers

3

You can use with:

with (G) {
  console.log(data);
}

The with is not widely used, nor recommended to use, as it puts all the properties of the object you are specifying as if they were global, which generates errors and hinders finding the.

Remembering further, that for the above reason the use of with is not allowed in restricted mode ('use strict'), although it is allowed on Node.js. Soon enough for these problems the use of it will work in your case.

  • Even if the with may cause bugs and has a negative effect on program performance.

2

I believe you want to do this:

file js.

module.exports = {
   DATA: "MY DATA"
}

app js.

var f = require('file.js');
console.log(f.DATA); // MY DATA

1

You could use a module that already comes in the core of Node.JS called vm.

For example:

var vm = require('vm');
var fs = require('fs');

var testFile = fs.readFileSync('./test.js');
var app = require('./app.js');

var local = {};
var ctx = vm.createContext(local);

// Essa função vai executar o código do `test.js`
// e todo parâmetro do objeto `local` será utilizado
// como contexto (variáveis locais)
vm.runInContext(testFile,ctx);

// Você poderá acessar o contexto manipulado
console.log(ctx);
  • 1

    Interesting his answer, however he specified that he did not want to use VM. :)

  • I didn’t see this detail. But anyway it is the tip. I use VM in several solutions of mine and hardly find any problem. Usually problems with VM you find when you need to do some isolation.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.