6

I just noticed something and would like to understand why node behaves in this way.

I have 2 files like so:

src/api/index-api.ts src/worker/index-worker.ts

They both have a simple console.log('Started xxx')

What I noticed was when I ran node build/api/index-api.js - I see both Started API and Started Worker in the console.

I figured out that in src/api/index-api.ts there is an import statement to use a function from src/api/index-worker.ts:

import { getContentFunction } from '../worker';

So I can see why they both get called.

But what exactly is the actual working of this - I mean what exactly happens and why is this so? As far as I was aware I'm just importing a specific function.

Thanks.

2 Answers 2

2

I assume your console.log call is at the root of your src/worker/index-worker.ts file.

When you import a function, any declaration within the target file's global namespace is also ran since it may also instantiate variables per example. Importing a single function doesn't prevent that, it only means you want to keep a reference only to the specified function and not to all of them. It also allows you to import said function into your global namespace instead of having worker.getContentFunction per example.

TL;DR: your worker file still runs entirely, your import only decides on which references you keep.


Note about CommonJS: the module.exports = {...} statement at the end of the file sets what the file exports, which is ran like any other code in it. If an imported file didn't run entirely, such a statement would certainly be useless in itself. The interpreter has to know what's in the file so it can do whatever you asked it to do.

Sign up to request clarification or add additional context in comments.

Comments

0

If I understand right. You want to call second file from first file. Try:

First file :

const {} = require("./second_file.js")

Second file :

console.log("Second file is working")

1 Comment

No - I just want to call a specific function from another file. Its calling the function file in my import - its just that it runs the entire file as well.