Require a single function - javascript

i am trying to export a file that has some configuration of my jwt, so i need to get those in my router
my exported function:
module.exports = {
'secret': 'sdasda',
'expirationTime': 60*60*24*4
};
requiring the function
var jwtConfig = require('../config/jwt');
and i get this error: Cannot find module './config/jwt'
the config folder is 1 path above, and the jwt file is inside :S
Any tip?

Related

Accessing non-existent property of module exports inside circular dependency

i'm having an circular dependency warnings in my node project that caused by index.js file that i wrote to combine some exports, the file look like this: path: utils/index.js.
const mysql = require('./mysqlDB');
const logger = require('./logger');
const ServerError = require('./ServerError');
module.exports = {
mysql,
logger,
ServerError
}
so I can import those in other files like this (lets said its called user.js):
const { logger, mysql, ServerError } = require('../utils');
so now if im requring user.js in another file thats include also things from utils.js
im getting the circular dependency warnings and errors after that...
when i deleted the index.js file that I wrote and requried the utils directly int my user.js file the warnings gone.
I'm not sure what I do wrong.
Thanks.

overwrite config file in nodejs - best practice?

Wondering what would be the best practice for my case.
I have a variable I need to set its value on app load and access this value many times across my code. what is the best way to get this value?
Right now I'm just overriding a config file property. Does a global variable is better? Is there another way to do this?
The priority standard for configs IMHO is:
command line parameter
environment var
local config file
global config file
if no cli parameter found, fall to look into environment vars, then local config file, then global
I do this.
Put the variable in .env file:
# .env
APP_PORT=4000
In my app source code, I create a file named constants.js:
// constants.js
import { load as loadEnvVars } from 'dotenv'; // run `npm i dotenv` to install
// load the .env file content to process.env
loadEnvVars();
// export the variables I need
export const APP_PORT = process.env.APP_PORT || 3000;
I import that file when I need it like this:
// server.js
import Express from 'express';
// import the constant
import { APP_PORT } from './constants';
const app = Express();
app.listen(APP_PORT, () => console.log('server deployed');

include bundle compiled with webpack to use in another js file

I have the following structure of my app:
index.js
const app = require("./app")
exports.api = app(...)
app.js
//all the imports goes here
//and exporting the main function
module.exports = app => {...}
Now I need to bundle app.js with webpack but index.js must stay intact
The question is, after bundling the app.js, how can I require it's main function app from index.js?
After webpacking app.js I'm getting error in index.js that says "app is not a function" which makes sense since app.js content is now wrapped in webpack staff.
Any suggestions are much appreciated.
Your "app" bundle needs to be exported as a commonjs.
module.exports = {
//...
output: {
library: 'app',
libraryTarget: 'commonjs',
}
};
The return value of your entry point will be assigned to the exports object using the output.library value. As the name implies, this is used in CommonJS environments.
So, in your index.js you can require('./dist/bundle-name.js').
seems to be a hack, but I made it work by adding an intermediate file and adjusting app.js and index.js like below:
index.js
const app = require("./bundle").app //changed to named import
exports.api = app(...)
bundle.js //an intermediate file which is now an entry point for webpack
import app from "./app"
exports.app = app
app.js
//all the imports goes here
//and exporting the main function
export default app => {...} //changed to default export
If anyone has explanation on why it works this way and how to simplify it without adding that bundle.js file, you are very welcome to comment!

Unable to import app.js in other modules in expressJs

I am Unable to import app.js in other modules in expressJs. It's importing but i am unable to use functions defined in app.js file
Code i have is this-
I have this
app.js
var app = express();
var expressWs = require('express-ws')(app);
.
.
.
wss= expressWs.getWss();
// console.log(wss); // works fine
app.getWss=function(){
return "hello";
};
app.listen(3001);
module.exports = app;
in a file inside /socketroutes/socketroutes.js
var app = require('../app');
console.log(app); // prints an empty object {}
console.log(app.getWss()) // returns undefined function and doesn't work
I want to use some variables or functions defined in app.js in another modules. because instance of websocket server should be created only once. i cannot create instance of wss in every module.
It's mostly because of a circular dependency.
Try moving the module.exports line to the beginning of the app.js file.

How to make object references available in Node modules?

I have an Express.js web app. In the main app.js file, I require() a bunch of third party dependencies. Recently I've started extracting parts of my app.js code into separate modules, e.g.
// in app.js
var users = require('./modules/users');
// and then e.g.
// users.add(doc);
Inside my modules, I sometimes need to use objects that are available in my main app.js file and I'm wondering what's the best way to pass references to those object to my modules.
My current approach:
// in app.js
// pass needed object references in initialization step
users.init([db, logger]);
and
// in modules/users.js
var db, logger;
exports.init = function (deps) {
db = deps[0];
logger = deps[1];
};
Does this approach make sense? Is there a better way to perform this?
Sure, just use modules! :)
// db.js
// create db instance here rather than in app.js
module.exports = db;
And
// logger.js
// create logger instance here rather than in app.js
module.exports = logger;
Then
// app.js
var db = require('./db');
And
// lib/somewhere.js
var db = require('../db');
This way you're able to rely on the CommonJS dependency injection system rather than on doing the dependency injection all by yourself (passing references around instead of requireing a module into yours).
The reason why this works as expected is that modules are only interpreted once, so if you instantiate everything once as opposed to using a factory function, it just works.
You should just be able to require modules as normal:
// users.js
var db = require('./db');
exports.init = function() {
// use db in here
};
However, sometimes this isn't possible and you will need to explicitly pass in the module.
One way to do it is to pass in dependencies when you require the module:
// users.js
module.exports = function(db, logger) {
return {
init: function() { /* use db and logger in here */}
};
}
// app.js
var db = ...;
var logger = ...;
var users = require('./users')(db, logger);
users.init();
This is the pattern that I personally prefer, I think it's cleaner to pass dependencies into the require than into some init method like you have in your example.
You'll see this done in ExpressJS code quite a lot, for example when we have all our routes in another file and need to pass our app instance around:
require('./routes')(app);
If you need something to be initialized specifically in app.js rather than their own module you can export them from app.js and then require app.js:
// app.js
var db = require("db"),
logger = require("logger");
// do your initialization with db and logger
module.exports = { db: db, logger: logger };
and then:
// users.js
var db = require("./app").db,
logger = require("./app").logger;
// use db and logger
This works because as #Nico mentioned, modules are interpreted once and app.js will not be interpreted each time it is required from elsewhere.

Categories

Resources