Monday, May 13, 2024
 Popular · Latest · Hot · Upcoming
188
rated 0 times [  195] [ 7]  / answers: 1 / hits: 19199  / 9 Years ago, thu, april 9, 2015, 12:00:00

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?


More From » node.js

 Answers
5

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);

[#67133] Tuesday, April 7, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
clarkulisesa

Total Points: 422
Total Questions: 93
Total Answers: 112

Location: Austria
Member since Thu, Jan 7, 2021
3 Years ago
clarkulisesa questions
Mon, Feb 24, 20, 00:00, 4 Years ago
Mon, Aug 12, 19, 00:00, 5 Years ago
;