简体   繁体   中英

Two variables refers to same config.js File using require (Reference Problem) in Node.js

Hello i have this scenario in Node.js

// config.js
module.exports = {
    dataUrlTest: "http://www.google.com",
};

#!/usr/bin/env node
//main.js

var config = require("./config.js");
var editConfigFile = require("./config.js");

console.log();
console.log(config["dataUrlTest"]); // output: http://www.google.com
console.log(editConfigFile["dataUrlTest"]); // output: http://www.google.com

editConfigFile["dataUrlTest"] = "test";

console.log();
console.log(config["dataUrlTest"]); // output: test
console.log(editConfigFile["dataUrlTest"]); // output: test

When i run "node main.js" the output is as follows:

http://www.google.com
http://www.google.com

test
test

as far as i understood from Node.js require function, it passes reference of the file not copying the file to the variable!

My Question is That, is there a way to have a copy of the file instead of having its reference?

I wanna change editConfigFile as value without affecting config variable,

Is there such thing?, i researched about it, didn't find a solution, any ideas? i'll be grateful.

Since you are importing an object, you get a reference. The require function basically imports the exported object(which is module.exports).

Objects are always referenced and not copied in JavaScript. This is not specific to node but to JavaScript in general. This means that both 'config' and 'editConfigFile' point to the same object.

One way to resolve this is to copy an object using Object.assign(). Here is how you can create a copy:

var config = Object.assign({}, require("./config.js")); //This line basically copies module.exports into a new empty object and returns that the config variable
var editConfigFile = Object.assign({}, require("./config.js"));

Now both config and editConfigFile are new objects and will not reference the old object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM