IgorAlves
IgorAlves

Reputation: 5540

Javascript - How to export a function and use it inside the same model.js file?

I am from php oop develoment and I know that there are many ways to create classes in JS. I need a support from a JS developer to solve this issue.

This is the scenario: I'm creating an AWS lambda function with nodeJS. I have a model called here as model1. Inside this model I want to export some functions. Some others will be used internally (like a private method in oop php).

model1.js

'use strict'
const { var1 } = require('../utils/...')
const { var2 } = require('../utils/...')
...

exports.fn1 = async (par1) => { ... }
exports.fn2 = async (par2) => { ... }
exports.fn3 = async (par3) => { //This could be used outside and inside this file
let someVar = await someMysqlstatement ...
}
exports.fn4 = async (par1) => { //Would like to use fn3 here
let someVar2 await f3(par3)
}

I want to know if it is possible to export fn3 and make it available in the module1.js at the same time. If this is not a good approach what it would be?

Upvotes: 1

Views: 1424

Answers (1)

Yousaf
Yousaf

Reputation: 29282

You can define the functions first

const fn3 = async (par3) => { ... }

and then export the ones you want to export at the end of the file:

module.exports = {
   fn3,
   ...
}

Note that above export statement will replace the module.exports object. Instead of replacing it, you can add new properties to it as shown below:

exports.fn3 = fn3;
exports.fn4 = fn4;
...

Separating the function definition and the export statement will allow you to use the function fn3 inside the module1.js file.


Also note that nodeJS also supports ES modules.

With ES modules, you can export your functions as named exports like:

export const fn3 = async (par3) => { ... }

and if you want to use any of the exported function in the same file, just use its name.

Upvotes: 2

Related Questions