Ways to export module - javascript

Imagine this code:
var authenticate = (req, res, next) => {
...
};
Can I export the above code like these?
module.exports = {authenticate}; or module.exports = authenticate;
Can I import above code like these?
var {authenticate} = require('./middleware/authenticate'); or var authenticate = require('./middleware/authenticate');

This should solve all your troubles: https://flaviocopes.com/commonjs/
exporting value:
autheticate.js
module.exports = authenticate;
other-file.js
const authenticate = require('./autheticate.js')
or exporting object
autheticate.js
module.exports = {authenticate};
other-file.js
const {authenticate} = require('./autheticate.js')

Related

Problem with adding imported function into exported function

So basically I want this block:
const {someFunction} = require("/somePath");
exports.exportedFunction = (req, res) => { someFunction() }
to work like this block:
exports.exportedFunction = (req, res) => {
const {someFunction} = require("/somePath");
someFunction();
}
But without repeating the imports. How to prevent repeating imports into every single export? I want to have one import from which I can use the function into every export without importing exactly into exports. Is that even possible?
UPDATE: okay, there's small update. I have made a minimum requirement problem recreation and it looks like this:
//index.js
const express = require("express");
const app = express();
const router = require("./router");
exports.exportableStuff = () => {
return [1,2,3];
};
app.use("/", router);
app.listen(3000, () => {
console.log("i am listening");
});
//router.js
const express = require("express");
const router = express.Router();
const controller = require("./controller");
router.get("/", controller.testModule);
module.exports = router;
//controller.js
const {exportableStuff} = require("./index");
exports.testModule = (req, res) => {
console.log("it has been done");
exportableStuff();
res.send("<h1>hello, user</h1>");
}
UPDATE2: I actually managed to fix the closures myself. What I actually did to make this work is changing this:
const {exportableStuff} = require("./index");
Into:
const model = require("./index");
And call the function in my controller with model.exportableStuff().
Problem oficially solved, but if you have better idea, I'm all ears.
According to your comment, I think you might want to do following thing?
// index.js
module.exports = { someFunction }
// router.js
// case1
const { someFunction } = require("./index.js")
someFunction() // it will work
// case2
const index = require("./index.js")
index.someFunction() // it will work
But, if you want to export your someFunction to another exports
then use new function, you need to do like this.
// another.js
const { someFunction } = require("./index.js")
exports.exportedFunction = someFunction
// router.js
const { exportedFunction } = require("./another.js")
exportedFunction() // it will work

importing modules node.js function overrides another function even without importing

in the following code i'm using expresjs
//index.js
app.use('/',routes());
//app/routes.js
module.exports = function() {
express = require('express');
const loggedUserProfileController = require('../controllers/LoggedUserProfile');
const userProfileController = require('../controllers/userProfile');
const router = express.Router();
router.post('/get-logged-user-profile', loggedUserProfileController.getLoggedUserProfile());
router.post('/get-user-profile-data', userProfileController .getUserProfile());
return router;
}
controllers
//controllers/loggedUserProfile.js
module.exports =
{
getLoggedUserProfile:function(){
return getLoggedUserProfile:function= (req, res, next) => {
getUserCustomData();
}
}
getUserCustomData(){console.log('logged user')}
//controllers/userProfile.js
module.exports =
{
getUserProfile:function(){
return getUserProfile:function= (req, res, next) => {
getUserCustomData();
}
}
getUserCustomData(){console.log('user')}
the output is 'user'
the second getUserCustomData overrides the first one how is that possible regarding that i didn't import it in module.exports
Yes this is possible. A function definition is hoisted, declared, and assigned. If you define another in the same scope after the previous one, the new definition will now overwrite the original.
Identifiers used in function statements/definitions are not constants and are therefore subject to re-assignment. If you want it to remain static after creation you can do const getUserCustomData = function () { ... } instead and the second attempt to re-assign will throw an error for you.

How to export class instance in Node?

Let's say, i have a class instance
const User = require(./User);
const id = '123456',
secret = '8787';
const user = new User(id, secret)
module.exports = user;
The problem is that whenever i import user, it just returns an empty object.
Why is this occurring and what should i do in this case?
This is what i'm using for testing
index.js file
const OAuthClient = require('disco-oauth'); //class disco-oauth
const credential = require('./credential.json');
//class instance
const oauthclient = new OAuthClient(credential.id,credential.secret);
console.log(oauthclient); //Working fine in here
module.exports = oauthclient; //exporting instance
test.js file
const oauthclient = require('./index')
console.log(oauthclient) //prints {}
you should make file with name User.js and copy this code :
class user {
constructor(id, secret){
this.id= id,
this.secret=secret
}
}
module.exports = user;
and your file is ok for require User class (yourFile.js)
const User = require(./User);
const id = '123456',
secret = '8787';
const user = new User(id, secret)
module.exports = user;
and you can make test.js file for import this user (yourFile.js) :
const user = require('./yourFile.js')
console.log(user)
I think the problem is in how you export your class,
seems like you used module.export = User instead of module.exports= User
My node server is running in index.js file and i was trying to export the class instance from that file, that's why it didn't work.
Previous code
const http = require('http'),
bodyparser = require('body-parser'),
OAuthClient = require('disco-oauth');
const app = require('./Api/api');
const credential = require('./credential.json');
const oauthClient = new OAuthClient(credential.id, credential.secret);
oauthClient.setScopes(['identify', 'guilds', 'connections']);
oauthClient.setRedirect(credential.redirect);
app.use(bodyparser.urlencoded({extended: false}))
app.use(bodyparser.json())
const server = http.createServer(app),
PORT = 80;
server.listen(PORT,'0.0.0.0', () => {
console.log(`running on port ${PORT}`);
})
module.exports = {
oauthClient
}
I removed OAuthClient from index.js and moved it in separate file and it's working now.

koa router doesn't work, sends 404

If I send POST such /image/cover or /image/sub/ from client, the router function doesn't work at all so It sends 404. It's supposed to work but I literally have no idea. I never had this case It just doesn't work for no reason.
router
import Router from 'koa-router'
const router = new Router({ prefix: '/image' })
router.post('/cover', async (ctx, next) => {
let URLpath = ctx.request.body.files.cover.path
ctx.body = { url: URLpath }
})
router.post('/sub', async (ctx, next) => {
let URLpath = ctx.request.body.files.sub.path
ctx.body = { url: URLpath }
})
export default router
log
<-- POST /image/cover
--> POST /image/cover 404 33ms -
import code (UPDATED)
router/index.js
import compose from 'koa-compose'
import accountRouter from './account'
import mypageRouter from './mypage'
import imageRouter from './image'
import postRouter from './post'
const routes = [
accountRouter,
mypageRouter,
imageRouter,
postRouter
]
export default () => compose([].concat(
...routes.map(r => [r.routes(), r.allowedMethods()])
))
app.js
import Koa from 'koa'
import serve from 'koa-static'
import logger from 'koa-logger'
import views from 'koa-views'
import session from 'koa-session'
import passport from 'koa-passport'
import bodyParser from 'koa-body'
import path from 'path'
import routes from './routes'
import config from './config'
import form from './util/formidable'
import mongoose from 'mongoose'
mongoose.Promise = global.Promise
mongoose
.connect(config.MONGODB_URI)
.then(startApp).catch(::console.error)
function startApp() {
const app = new Koa()
const port = process.env.PORT || 3000
const dist = __dirname + '/views/'
console.log(form)
const bpOption = { IncomingForm: form, multipart: true }
app.keys = ['secret', 'key'];
require('./util/passport')
app
.use(logger())
.use(serve(dist))
.use(session({}, app))
.use(bodyParser(bpOption))
.use(passport.initialize())
.use(passport.session())
.use(views(__dirname+'/views', { extension: 'pug'}))
.use(routes())
app.listen(port, () => console.log(`[!] Server is Running on ${port}`))
}
you need help function:
// #help function record route table map
'use strict';
const fs = require('fs');
const resolve = require('path').resolve;
module.exports = function record(router, filename) {
const routeTable = fs.createWriteStream(resolve(__dirname, filename));
routeTable.write(`Update Date: ${new Date().toString()}\n\n`);
for (let len = router.stack.length, i = 0; i < len; i += 1) {
const route = router.stack[i];
routeTable.write(`URL:${route.path}\t${route.methods.join('|')}\n`);
}
routeTable.end();
};
then you can involve it by
const record = require('./record');
record(routeApp, '.routerc')
you will get .routerc file(route map) with content such as:
URL: /a/c/c POST
URL: /b/a/d GET
it can help you to solve problem. maybe work. good luck!

Variable does not return desired object

I am building an Express app. I currently have an error in the following file, factoryRepository.js
let appReference = null;
module.exports.init = (app) => {
appReference = app;
};
module.exports.getRepositoryFactory = () => {
let repositoryFactory = {
getUserRepository: () => {
return require("./UserRepository").init(appReference.get('models').User);
}
};
return repositoryFactory;
};
appReference.get throws a TypeError because appReference is still null even after I have called module.exports.init somewhere else.
I have tried to make a function that returns appReference so I can see in what state it is. I have been able to get app rather than null, it is only in the context of getUserRepository that it stays null.
The faulty line is only called when I ping a certain route.
EDIT:
This is app.js, the context from which module.exports.init is being called
import express from 'express';
import passport from 'passport';
import config from './config/config';
let app = express();
// Setup models
app.set('models', require('./app/models'));
require('./app/repo/repositoryFactory').init(app);
// Setup config
require('./config/init')(app);
// Setup routes
require('./app/routes')(app, passport);
// Setup passport
require('./app/auth')(passport, config);
// Route to ends
require('./config/endpoints')(app);
export default app;
public.js is the logic given to my router, and it is here where I call the faulty code with repositoryFactory.getUserRepository()
let repositoryFactory = require('../repo/RepositoryFactory').getRepositoryFactory();
module.exports.doLogin = (req, res) => {
let success = () => {
res.redirect('/');
};
let error = (message) => {
res.status(500).json(message);
};
let userRepository = repositoryFactory.getUserRepository();
userRepository.findOrCreate({
facebookId: req.user.id,
displayName: req.user.displayName
}, success, error);
};
module.exports.doLogout = (req, res) => {
req.logout();
res.json({
success: true,
message: 'You\'ve succesfully logged out.'
});
};
This looks like a scope issue. Let's say we simplify your three files as follows, and also put them all in the same directory (for simplicity here):
app.js:
'use strict';
const express = require('express');
let app = express();
require('./repositoryFactory').init(app);
const myPublic = require('./public');
repositoryFactory.js:
'use strict';
let appReference = null;
module.exports.init = (app) => {
appReference = app;
};
module.exports.getRepositoryFactory = () => {
return appReference ? 'I have an app reference!' : 'No app reference!';
};
public.js:
'use strict';
let repositoryFactory = require('./RepositoryFactory').getRepositoryFactory();
console.log(repositoryFactory);
This is going to log No app reference! because the repositoryFactory is not a singleton. The repositoryFactory instance in app.js is a different instance than the repositoryFactory instance in public.js.
One solution would be to pass a parameter for the repositoryFactory instance. repositoryFactory.js would be unchanged, but app.js might look like this:
'use strict';
const express = require('express');
let app = express();
const repositoryFactory = require('./repositoryFactory')
repositoryFactory.init(app);
const myPublic = require('./public');
myPublic.init(repositoryFactory);
myPublic.log();
And the corresponding public.js might look like this:
'use strict';
let repositoryFactory = null;
module.exports.init = (myRepositoryFactory) => {
repositoryFactory = myRepositoryFactory.getRepositoryFactory();
}
module.exports.log = () => {
console.log(repositoryFactory);
}

Categories