I would like to export one function in node and call it in another file. Somehow it is always executing the whole code in the exporting module (not only the function exported).
//file: test.js
module.exports = function () {
console.log("Hello");
}
console.log("Hello2");
//file: test2.js
var test = require("./test");
test();
// Desired Output: Hello
// My actual Output: Hello2 Hello
Can somebody please explain, why it is also running the second log (Hello2) although this log is not within the exported brackets?
When you require a file, you import the entire file and it gets executed. Since console.log('Hello2'); isn't defined in a function, it gets executed when the file is required.
This is why you should see Hello2 first. And then you call the test function which executes and prints out Hello.
Your output should be:
Hello2
Hello
Try to do a named export,
for example:
module.exports = function first () {
console.log("Hello");
}
and in your test2.js:
var test = require("./test");
test.first();
When you do var test = require("./test"); you are requiring the whole file, rather than just the module you exported. In the file where you wish to use the function, you need to import the function from the other file.
Try doing this:
//file: test.js
module.exports = function () {
console.log("Hello");
}
console.log("Hello2");
//file: test2.js
import { test } from './test'
test();
Related
When one imports a specific value from another file, does the entire file that has been exported from run in the file importing? For example if I wanted to import the function "hello" from file b, into file a, would file b run in file a?
An example being:
File A:
import {func} from 'fileB.js';
File B:
let func = function(){...}
console.log(`Hello`);
export {func};
Would Hello appear in the console of file A, and if it would, under what circumstances. For example, would it be when the import statement is run, or when the func is called. If it would not run, are there any ways to make it so it does. For example if I exported the entire file (if that's possible) would the Hello appear under certain circumstances?
The imported file will be run. An easy way to both understand and remember this is dynamic exports:
export let Foo;
if (window.Foo === undefined) {
Foo = class Foo { ... }
} else {
Foo = window.Foo;
}
In order to know what was exported to begin with, the code needs to be run. Otherwise, it would be equal to solving the halting problem.
if you are using webpack import or require
declare like this
const Logger = function() {
}
export { Logger };
use it
import { Logger } from '../class/Logger';
let logger = new Logger();
I want to run several code before the code inside import syntax gets executed.
Example
file-1.js
console.log('Inside File 1')
import './file-2.js'
file-2.js
console.log('Inside File 2')
Output
Inside File 2
Inside File 1
The output I expected
Inside File 1
Inside File 2
Environment
Node JS v12.19.0 with Module configuration
Real Case
file-1.js
process.env.SHARED_DATA = 'Hello world'
import './file-2.js'
file-2.js
console.log(process.env.SHARED_DATA)
Output
undefined
You can define the env data in separate file. The import syntax will run in the order against the other imports as #loganfsmyth says.
Example
main.js
console.log('Inside main.js file')
import './set-env.js'
import './file.js'
set-env.js
console.log('Inside set-env.js file')
process.env.SHARED_DATA = 'Hello world'
file.js
console.log(process.env.SHARED_DATA)
Output
Inside set-env.js file
Hello world
Inside main.js file
The best way I find is to use top-level await with dynamic import.
process.env.SHARED_DATA = 'Hello world';
await import('../index.js');
In JavaScript the lines don't necesarily wait for the line before to end. One way to solve this issue of yours is to put the file-1.js into a async function:
async function f() {
process.env.SHARED_DATA = "Hello world";
return Promise.resolve(1);
}
f().then(() => {import "./file-2.js"});
By calling this function you can make sure the import waits for the f function to end! Then running the arrow function. Hope this helped if you want to read more about this topic here you go. https://javascript.info/async-await
I try to use function from another Javascript file in my Gulpfile, but cannot make it work so far.
The file I need to access in Gulpfile:
var hello = function(){
console.log('Hello')
}
And the way I require it in my Gulpfile:
var tools = require('./public/js/tools.js');
gulp.task('create_subscriptions', function(){
tools.hello();
});
tools.hello() is not a function is triggered.
What do I do wrong here?
Edit
I did
module.exports = {
hello: hello()
};
Whats the difference wit exports.hello = hello?
You didn't export anything from your module. Local variables are not exposed, you need to explicitly mark them as public.
exports.hello = hello;
hello: hello()
You have () after the variable holding the function. You are calling it and assigning the return value (which is not a function) to your hello property.
I've recently started writing CommonJS modules but facing issues in requiring modules. Why is storage.js unable to reach the example module which I have required? What is the proper way to require a dependent module in this case?
EDIT: Included more information because the previous question omitted hello.js, which I thought wasn't the cause of the problem. Seems like including it causes a uncaught type error. Also, this is part of the code for a chrome extension, and main.js is the content script.
// main.js
var hello = require('./hello');
var storage = require('./storage');
var example = require('./example');
storage.store();
// storage.js
var example = require('./example');
module.exports = (function() {
function store() {example.ex();}
return {store: store};
})();
// example.js
var storage = require('./storage');
module.exports = (function() {
function ex() {
console.log('example');
}
return {ex: ex};
})();
// hello.js
var example = require('./example'); // <<<< Including this gives Uncaught TypeError: example.ex is not a function
module.exports = (function() {
function hello() {
console.log('hello');
}
return {hello:hello};
})();
Not a direct answer to your question, but Browserify will wrap in a self-invoking function for you. You can simplify your lib files:
// main.js
var storage = require('./storage');
storage.store();
Because you don't use hello or example, don't require them.
// storage.js
var example = require('./example');
function store() {example.ex();}
module.exports.store = store;
No need to go through the self-invoking function here.
// example.js
module.exports.ex = ex;
function ex() {
console.log('Example');
}
This doesn't use storage, so don't include it.
hello.js does nothing but trigger the circular dependency, remove it.
In your updated code, you have a circular dependency between storage.js and example.js. Because you don't use anything from storage in example, you can just remove that require. I still think you should remove the self-invoking functions, as that's already part of commonjs.
When loading a module, Commonjs will only execute the file a single time. Everything on module.exports is then cached for future calls. When you include the circular dependency for the first time, the module loader sees that its currently being loaded, and you don't get any results back. Subsequent calls will complete as normal.
I am writing some logic in fileB.js that needs to call another function declared in fileA.js. fileA.js declares a function called abc(). How can I call abc() from fileB.js.
Both fileA and fileB are in the same directory.
Thank you
Ps. I am not using this with HTML. I am just running it locally as part of another project I am working on. I am now using node to run it from terminal. But I am not using anything else in these two files. I just have a bunch of really simple functions. No node.js modules or anything...
Node.js isolates each file as a module, giving each their own local scope to define essentially "private" functions and vars.
With this isolation, fileA will need to export abc in order to share it with other files/modules:
function abc() {
// ...
}
exports.abc = abc;
Then, fileB can require() fileA with a relative path (. referring to the current directory) and use its exported function:
var a = require('./fileA');
a.abc();
If you are using node, then in fileA:
module.exports = { abc: abc } //assuming that abc holds a reference to your function, declared somewhere above
Then, in fileB you require fileA and use what you exported:
var fileA = require('./fileA.js');
fileA.abc();
Since you're running it in NodeJS, I'd suggest doing the following at the top of fileB.js:
var fileA = require( './fileA.js' );
However, in order for this to work, the functions you want to use in fileB.js should be exported from fileA.js. To do this, lets assume that the function abc() is what you want to access:
// In fileA.js:
function abc() {
// ... do something ...
}
module.exports = abc;
If you want multiple functions/variables/objects available to fileB.js, you can export them all as one object:
// In fileA.js
function abc() {
// ... do something here ...
}
var myObject = {
propOne: 'foo',
propTwo: 'bar
};
module.exports = {
abc: abc,
myObject: myObject
};
Then, within fileB.js:
// Import the fileA object you just created.
var fileA = require( './fileA.js' );
// Save references to abc and myObject
var myObject = fileA.myObject,
abc = fileA.abc;
Just include both the JS files in the HTML and then simply call them any function anywhere, it will work.