简体   繁体   中英

Import function from sister file Node.JS

I hope to explain this in a non-abstract way. I have a problem and I believe that I am pushing the boundaries of Node because there doesn't seem to be much documentation on this particular subject.

To start out, this is my file layout.

//main.js
var 1 = require('1.js');
var 2 = require('2.js');

The purpose of this first file is to load two child files into the process.

//1.js
console.log('Test');
module.exports = function msgUSR(text){
  console.log(text);
}

The purpose of this file is to create an export, this export could very obviously be imported into Main.js , however, I have a situation where I need to import a function from 1.js into 2.js without reloading the entire file into memory.

for example.

//2.js
var msgUSR = require('1.js');
msgUSR('blah');

The problem with this setup is that when you require 1.js, it reloads the entire file, including any code that isn't an export.

How could I only import the exports of a file without loading the unrelated code.

Thank you! I know someone has a solution to this.

EDIT: I understand that the code here wouldn't replicate any useful data. My point is, how do I require a function in another JS file that is already required by a parent file. Instead of writing two long hefty functions that are exactly alike in two different files, I need to be able to call the function from a sister file. Here is why this is an issue. If you were to require the file after the parent has required it, 'Test' would appear two times, symbolically meaning that other complex code would also be loaded. My hopeful result from this question would be a result where I could require the file in such a way as to only import a function from it. Thanks again.

The problem with this setup is that when you require 1.js, it reloads the entire file, including any code that isn't an export.

When you require something the file will be loaded once and then is cached

How could I only import the exports of a file without loading the unrelated code?

You would never have to reload the file once it is already required since Node will use the cached version.

The require function normally has 5 steps:

  1. Resolving: To find the path of the file
  2. Loading: To determine the type of the file content
  3. Wrapping: To give the file its private scope. This is what makes both the require and module objects local to every file we require.
  4. Evaluating: This is what the VM eventually does with the loaded code.
  5. Caching: So that when we require this file again, we don't go over all the steps another time.

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