I have a very basic function that looks like this, it is in a file called functions.js
function echo(input){
process.stdout.write(echo);
}
When I add the file and call echo()
like so:
Main file:
require("functions.js");
require("another_file.js");
another_file.js
echo("hello!");
It is giving me the following error:
ReferenceError: echo is not defined
Is there a way for me to make a function that is global like that without havingin to use exports
?
Node. js global objects are global in nature and they are available in all modules. We do not need to include these objects in our application, rather we can use them directly. These objects are modules, functions, strings and object itself as explained below.
Global variables are variables that can be declared with a value, and which can be accessed anywhere in a program. The scope of global variables is not limited to the function scope or any particular JavaScript file. It can be declared at one place and then used in multiple places.
Everything in JS is bound to containing scope. Therefore, if you define a function directly in file, it will be bound to window object, i.e. it will be global.
Inside functions.js
you'll have access to node's global
variable, which is like the window
variable in a browser. As Plato suggested in a comment, you can add this to the global by simply doing echo = function echo(input){ ... }
. However, this will throw an error if you're using strict mode, which is intended to catch common mistakes (like accidentally creating global variables).
One way to safely add echo
as a global is to add it to the global global
variable.
"use strict";
global.echo = function echo(input) {
process.stdout.write(input);
}
I think generally using exports
is better practice, because otherwise once functions.js
is included (from any other file) you'll have access to echo
in every file and it can be hard to track down where it's coming from.
To do so you would need to have your functions.js
look more like:
"use strict";
module.exports.echo = function echo(input) {
process.stdout.write(input);
}
Then in your main script do something like:
"use strict";
var functions = require("./functions.js");
functions.echo("Hello, World");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With