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

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;
};

In this way, I can export variables under the object G , and at the same time, I can access the variable directly write DATA without G . prefix.

Now, I want to test for app.js on test.js

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

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

Certainly, I could do like:

var DATA = G.DATA;

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

Is there any way to do this automatically?

So far, I've been pessimistic since

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

I'd like to avoid any var or eval solution node. I've tried them in the past, and had a lot of problems.

    
asked by anonymous 05.02.2014 / 00:40

3 answers

3

You can use with :

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

with is not much used, nor recommended to use, because it puts all the properties of the object you are specifying as global, which creates errors and hinders encounters.

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

    
05.02.2014 / 01:01
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
    
27.02.2014 / 22:29
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);
    
19.02.2014 / 02:54