Sankalp Sankalp - 10 months ago 52
Node.js Question

how to assign variable in module if I export it

I am trying to import file with

in another file. How would I set variable of imported file.

suppose 'sample.js'

var a = '';
var b = '';
export.funcA = function(){
export.funcB = function(){
export.funcC = function(){
//somewhere I am using a & b variable with dynamic values that need to be set run time.

var sample = require('sample.js');
//Now before using function `funcC` I want to dynamically set values of variable a & b.
so I can easily use `sample.funcC()`;

// I don't want to pass it using a parameter. because I am already assigning third to funcC so I can't set parameter.

Answer Source

You can export an object:

// sample.js
module.exports = {
  a: '',
  b: '',
  funcA: function funcA() {
  funcB: function funcB() {
  funcC: function funcC() {
    return this.a + this.c;

// script.js
var sample = require('sample.js');
sample.a = 'foo';
sample.b = 'bar';
sample.funcC(); // => 'foobar';