module.exports that include all functions in a single line - javascript

This is a follow-up question to In Node.js, how do I "include" functions from my other files?
I would like to include an external js file that contains common functions for a node.js app.
From one of the answers in In Node.js, how do I "include" functions from my other files?, this can be done by
// tools.js
// ========
module.exports = {
foo: function () {
// whatever
},
bar: function () {
// whatever
}
};
var zemba = function () {
}
It is inconvenient to export each and every function. Is it possible to have a one-liner that exports all functions? Something that looks like this;
module.exports = 'all functions';
It is so much more convenient this way. It is also less buggy in case one forgets to export certain functions later.
If not a one-liner, are there simpler alternatives that make coding more convenient? I just want to include an external js file made up of common functions conveniently. Something like include <stdio.h> in C/C++.

You can write all your function declarations first and then export them in an object:
function bar() {
//bar
}
function foo() {
//foo
}
module.exports = {
foo, bar
};
There's no magical one-liner though, you need to explicitly export the functions you want to be public.

I have done something like the following:
var Exported = {
someFunction: function() { },
anotherFunction: function() { },
}
module.exports = Exported;
I require it in another file and I can access those functions
var Export = require('path/to/Exported');
Export.someFunction();
This is essentially just an object with functions in it, and then you export the object.

A really old question but I just had to solve the same issue myself.
the solution I used was to define a Class inside the module to contain all my functions and simply export an instance of the class.
classes.js looks like this:
class TestClass
{
Function1() {
return "Function1";
}
Function2() {
return "Function2";
}
}
module.exports = new TestClass();
app.js looks like this:
const TestClass = require("./classes");
console.log( TestClass.Function1);
just keep adding more functions to the class and they will be exported :)

It is worth noting that in ES6, you can now export functions like this:
export function foo(){}
export function bar(){}
function zemba(){}
Simply write export before the functions you want to export. More information here.

If you use ES6 you can do something like that:
function bar() {
//bar
}
function foo() {
//foo
}
export default { bar, foo };

const fs = require("fs")
var ExportAll = {
deleteFile : function deleteFile(image,folder="uploads"){
let imagePath = `public/${folder}/${image}`
if (fs.existsSync(imagePath)){
fs.unlinkSync(imagePath)
}
},
checkFile : function checkFile(image,folder="uploads"){
let imagePath = `public/${folder}/${image}`
if (fs.existsSync(imagePath)){
return true
}
else{
return false
}
},
rand : function(min=1,max=10)
{
return Math.floor((Math.random() * max) + min)
}
}
module.exports = ExportAll

Import everything from a type module file that has functions that are exported.
Found here:
https://javascript.info/import-export
myfile.js
export function myFunction()
{
// ................
}
export function myFunction2()
{
// ................
}
myfile2.js - import everything that is exported in the file
import * as myFunctions from './myfile.js';
// Usage
myFunctions.myFunction();
myFunctions.myFunction2();

Related

Diff between exporting function as const and class method

Whats the diff between these two approaches of exporting and in which situations we go for exporting class and exporting function as const ? Which is ES6+ compatible?
// approach1.js
class Sample1 {
hello(visitorName) {
return `hello ${visitorName}`;
}
}
module.exports = Sample1;
And
// approach2.js
const hello = (visitorName) => {
return `hello ${visitorName}`;
};
module.exports = hello;
Test Class
// test.js
const Sample1 = require('./approach1');
const sample2 = require('./approach2');
async function start() {
const returnValueForApproach1 = (new Sample1()).hello('Name');
console.log(returnValueForApproach1);
const returnValueForApproach2 = sample2('Name');
console.log(returnValueForApproach2);
}
start();
Output:
hello Name
hello Name
You generally want to use a class when data gets stored on the instance - that is, when you need to refer to this in at least one of the methods. For example:
class Sample1 {
constructor(name) {
this.visitorName = name;
}
hello() {
return `hello ${this.visitorName}`;
}
}
const s = new Sample1('foobar');
// ... followed by some code, then
console.log(s.hello());
If you don't ever store data on the instance, using a class doesn't make a whole lot of sense, since it adds a bit of extra and somewhat confusing overhead without much reason. JavaScript isn't Java - don't feel like you have to tie everything to a class.
If you just have a single function, like in your example, then your second example of
const hello = (visitorName) => {
`hello ${visitorName}`;
};
module.exports = hello;
makes the most sense by far; just declare and export the function.
If you had a collection of functions not related to instance data, you could export an object with those functions, eg:
module.exports = {
fn1() {
// code
},
fn2() {
}
};
All of the code in the question and this answer uses ES6 syntax, so I suppose it's "ES6 compatible".

Exporting multiple functions with arguments

All I am trying to do is to export two functions from a module. One function taking an argument and the other with no argument:
function initClass(params)
{
return new Promise( (resolve, reject) => {
if (!wallet) {
wallet = new WalletClient(params);
resolve(wallet);
} else {
console.log('Wallet is initialized');
resolve(wallet);
}
});
}
function getInstance()
{
return wallet;
}
For initClass(params) only, I can do this as:
module.exports = (params) => {
initClass(params)
}
And then I call this as:
var init = require('./class.js')(params).initClass(params);
This works fine.
Now, for me to export getInstance() as well, I have tried to do the following but it doesn't seem to work.
module.exports = (params) => {
initClass(params),
getInstance
}
This complaints that there is no function getInstance.
Then I tried this:
module.exports.init = (params) => {
initClass(params)
}
module.exports.instance = {
getInstance
}
Then call them as:
var init = require('./class.js').init(params).initClass(params);
What is the proper way to export multiple functions like this?
Thank you.
You're making it more complex than needed. Once you have your functions defined, you can export it with this:
module.exports = {
initClass,
getInstance
}
To use it, you do this:
const init = require("./class.js");
init.initClass(params);
const instance = init.getInstance();
What you're exporting from the module is an object (which I've named init in the example above) that contains two functions. You don't have to pass arguments to the functions at the time you require.
module.exports is basically an object with keys which can refer to any variables/functions of your file.In your case,
module.exports.initClass = function (params){
...
}
module.exports.getInstance = function (){
}
When importing it
var init = require('./class.') // init object has two keys -> initClass and getInstance
init.initClass('abc')
init.getInstance()
If i'm understanding correctly you are trying to export multiple methods if that is the case simple use this.
module.exports = {
method: function() {},
otherMethod: function(parmas) {}
}
In your code use like this.
var init = require('./class.js');
init.method()
init.otherMethond(paramObj)
If you want below scenario you need to check out about method chaining.
var init = require('./class.js').init(params).initClass(params);

Call one function from another in custom node - NodeRED

I am trying to access the function from another file like below:
exp1.js
module.exports = function(RED) {
function expIn(config) {
//some code
}
}
I want to access "expIn()" in another file called exp2.js how can i achieve this??
please help me.
As is, you are not exporting expIn(). You are exporting the outer function in which expIn() is declared and defined. expIn() is just a local variable and cannot be accessed outside of the anonymous outer function you are actually exporting. To make it visible to other files, you either have to export it directly or define it on the exported function.
You're missing some code, but you have 3 options for accessing expIn() outside of exp1.js. First is to export it directly
exp1.js
module.exports = function expIn(config) {
// Code...
};
exp2.js
const { expIn } = require('exp1.js');
expIn({/*config*/});
Alternatively, you could add expIn() to the outer function's prototype. This is usually done when you want to export a class with several methods attached to it. You can do this one of 2 ways. First, the method most similar to what you're already doing is
exp1.js
module.exports = function ClassName(/*constructor args*/) {
this.expIn = function expIn(config) {
// Code...
};
// Other initialization...
};
Alternatively, you could define expIn() more explicitly on the prototype using this method:
exp1.js
function ClassName(/*constructor args*/) {
// Initialize class.
}
ClassName.prototype.expIn = function expIn(config) {
// Code...
};
module.exports = ClassName;
Regardless of which of the 2 methods you choose above, you would access it as
const ClassName = require('exp1.js');
let classInstance = new ClassName();
classInstance.expIn({/*config options/*});
One last method you could use is defining expIn() as a static method on the function class. This would look like:
exp1.js
function ClassName(/*constructor args*/) {
// Initialization code...
}
ClassName.expIn = function expIn(config) {
// Code...
};
module.exports = ClassName;
exp2.js
const ClassName = require('exp1.js');
ClassName.expIn(/*config options*/);
This i resolved by adding function out side the function(RED):
module.exports = function(RED) {
}
function expIn(config) {
//some code
}
And then exported as normal like :
module.exports.expIn = expIn;
then it starts working.
I am not sure whether this is a correct method or not but it serves my requirement.

Import a function from JS to JSX

I have a JS file containing this code:
module.exports = function loadMyFun() {
function activateSite($currentItem) {
...
}
...
}
And I want to import it into a JSX file, I tried to do it like this but I doesn't work:
import MyNav from './MyNav.js';
const top = MyNav.activateSite();
componentDidMount () {
var self = this;
MyNav.activateSite($(self));
}
...
I get this error:
Uncaught TypeError: _MyNav.default.activateSite is not a function
Any idea how to solve this?
activateSite is a variable that is locally scoped to the loadMyFun function.
It is not available outside the scope of loadMyFun.
It is not a property of the loadMyFun function object.
You cannot access it without rewriting the module.
e.g.
module.exports = function loadMyFun() {
};
module.exports.activeSite = function activateSite($currentItem) {
};
If the code you provided is actually the module you are trying to load, then there are a few problems with that module.
You are exporting a constructor loadMyFun, which you are not calling/instantiating after importing it.
If you would instantiate your constructor like this const myNav = new MyNav() you would have a instance of your exported constructor.
To make your activateSite function work, you would have to assign it to the instance itself and move it out of the local scope of loadMyFunc by assigning it like this: this.activateSite = function(){...}
If you dont need any information wrapped around your activateSite function I would recommend you export an object with your functions instead of the loadMyFun approach.
//myModule.js
module.exports = {
activateSite: function(){ ... }
}
//otherFile.js
import { activateSite } from './myModule.js' // With destructuring
activateSite()
import myModule from './myModule.js' // Without destructuring
myModule.activateSite()

es6 equivalent for module.exports

What's the ES6 equivalent for module.exports
I want to get the value of foo from an import statement
module.exports = {
foo: function (a) {
}
}
Tried:
export default {
foo: function (a) {
}
}
The way first one is imported is using:
var file;
var filename = root + "/" + fileStats.name;
file = require(path.resolve(filename));
I want to use ES6 import statement. I read somewhere that this isn't supported however would like to still know if there's a work around this.
Not sure what you're trying to do because in the code you supplied you did not consume the actual foo method from the object you imported.
But if I understand correctly, you could achieve this in one of 2 ways:
export default function foo(a) { };
and consume the module with:
import foo from './<filename>.js';
Or alternatively, don't use the default export:
export function foo(a) {};
and consume with:
import { foo } from './<filename>.js';

Categories