Code in required function doesn't execute correctly? - node.js

I'm havin trouble getting an exported function to run.
My secondary file looks like this:
require("dotenv").config()
// ...
function requestConsent(req, res) {
res.redirect(308, process.env.MY_URL + dictToURI(myHTTPparams)));
}
// ...
function dictToURI(d) {
doSomeStuff(d);
}
// ...
exports.requestConsent = requestConsent
My main file looks like this:
const api = require("./api.js")
const express = require("express")
const app = express()
// ...
app.get("/login", api.requestConsent);
// ...
When I execute this, dictToUrl works perfectly fine, but process.env.MY_URL always evaluates to undefined, even when I replace it with a string literal. It worked without issues before the functions to a seperate file.
How can I fix this? (Aside from moving it back)
As the function is in a required file, any breakpoints I set there are skipped and any console output is not visible (I'm using WebStorm 2018.3).

The problem wasn't in my code at all: My browser had a broken forwarding cached, therefor the code in question was never called in the first place.

Related

Exported object is empty

I'm struggling since 2 days on something that shouldn't block me.
Basically, I'm building a nodeJS app that uses Express.
In my main file (located in my root folder), i'm exporting some variables/consts, for the purpose of the example I replaced them like this :
// ./index.js
const test = 'test'
module.exports = { test }
... some express initialization/routers
I then have another file that I want to use the "test" variable in, so I require my main file :
// ./aaa/bbb/ccc/test.js
const { test } = require('../../../index);
const myRouter = require('express').Router();
myRouter.get('/', function (req, res){
console.log(test) // undefined
})
I don't really know why it would be undefined as I correctly exported it, and "imported" it through my require statement.
I also tried "consoling" the whole object that I should receive, and it's empty : {}
EDIT : my "main" script that i'm executing is indeed index.js, but I highly doubt it's the reason of the problem
I can't really find out what could be the problem, and I need to export some variable to access them in my project
Thanks!
I think you did it right. The problem may be that es6 features are not acceptable on your node version. Try it like: module.exports = { test:test }.

returning result from another nodejs file

i am working on a project in which a nodejs program calls another program in a separate file.
this is how i've added the two:
var ocr = require('./index.js'); //this imports the file
var arr = ocr.ocr_pan(); //this calls the function in that file
am not sure but I guess the problem is that the process resumes before ocr.ocr_pan() returns the result and var arr becomes undefined.
or there is some problem in returning the result from ocr.ocr_pan()
I simply use return.
and I have also tried this : How to return array from module in NodeJS
didn't work
what more can be done?
Assuming that this file is the same directory as index.js file, code in index.js should be something like this:
// Write your function
var ocr_pan = function() {
// Do whatever you like
return result;
};
// Export it, make publicly visible to other files
module.exports = {
ocr_pan: ocr_pan
};

Understanding ExpressJS application start-up

I am struggling with how application start-up works in Express. I am going to explain my use-case:
I have a configuration-Manager module which is used by all other application modules to load required configuration. I am setting configuration in app.listen:
app.listen(9000, function () {
try
{
config_manager.setSiteConfig();
console.log('settings..!!!')
}
catch(err)
{
console.log(err.stack);
}
});
In another module of the same application I call the Configuration-Manager function to load config, but it returns empty. Code is something like this:
var config_manager = require('configuration-manager');
console.log(config_manager.loadConfig()); // returns empty object {}
I am running the application using node app.js. The empty object gets printed first then ('settings..!!!'). Does Express compile the script before calling app.listen()? How do I make sure that my configuration is set before compilation/loading other files?
Express indeed first processes all statements in a file, basically anything that isn't in a function on startup.
In your case var config_manager = require('configuration-manager');
console.log(config_manager.loadConfig()); // returns empty object {} is executed before your app.listen because you are requering the config before the app.listen.
You're best off processing your configuration right after the first time it is required (if app.js is your main file, this means the first time it comes across a require statement pointing to configuration-manager in any file).
This should make your code work:
var config_manager = require('configuration-manager');
try {
config_manager.setSiteConfig();
} catch(err) {
console.log(err.stack);
}
console.log(config_manager.loadConfig()); // returns empty object {}
and then
app.listen(9000, function () {
console.log('settings..!!!', config_manager.loadConfig()) // Should correctly print your config
});
If this doesn't work the problem does not lay in the order of execution.

return value to app.js file in node js

I have two files, one called filename and the second called app.js, both files are on the server side. From filename.js filder I am returing a value string from ensureAuthentication method to app.js file, so i export the function:
function ensureAuthentication(){
return 'tesstestest';
}
exports.ensureAuthentication = ensureAuthentication;
in app.js file i do following
var appjs = require('filename');
console.log(appjs.ensureAuthentication);
result is always is undifined in console??! why is that any idea?
You should try this in your app.js -
var login = require('filename');
console.log(login());
or you can use this :
var login = require('filename')();
console.log(login);
Explanation: Whenever you are exporting a function using exports you need to execute it to get the return value from it.
Try this:
var appjs = require('filename');
console.log(appjs.ensureAuthentication());
note the () after the function call. This will execute your function. The console.log() call will then print the returned value.
Try this, make sure both files are in the same directory. You have a few errors with your code. Missing brackets, and not importing correctly in app.js.
filename.js
function ensureAuthentication(){ // You are missing the brackets here.
return 'tesstestest';
}
exports.ensureAuthentication = ensureAuthentication;
app.js
var appjs = require('./filename'); // You are missing the ./ here.
console.log(appjs.ensureAuthentication()); // Logs 'tesstestest'
Two problems with your code:
You need to require with a relative path (notice the ./):
var appjs = require('./filename');
To get the string value you need to invoke ensureAuthentication as a function:
console.log(appjs.ensureAuthentication());
UPDATE
This update addresses the screenshot posted in the comments.
In the screenshot you pasted in the comments, you have the following line:
module.exports = router
That assigns a different exports object to the module. So your local reference to exports is no longer the same object.
Change that line to
module.exports = exports = router
Which will preserve the reference to exports which you use next.
Here you go with the working code
filename.js
function ensureAuthentication(){
return 'tesstestest';
}
module.exports = {
ensureAuthentication : ensureAuthentication
}
app.js
var appjs = require('./utils/sample');
console.log(appjs.ensureAuthentication());

How to avoid memory conflicts on ExpressJS/Node.js

I'm using Express and Passport for node.js to build a simple web server, I coded a simple module and then I loaded the module inside a GET request, everything works great until more than one user access the request.
I use to believe that a "var" inside an "app.get" function was removed from memory after the function finished, but isn't the case, I use some local variables inside the external module and the values are being shared between users, the module looks like this:
var some_value=0;
function some_method(){
some_value++;
return some_value;
}
exports.some_method = some_method;
And the Express request code looks like this:
app.get('/someurl', function(req, res) {
var some_extermal_module = require('/some_extermal_module'); // <-----Right way?
var data = some_extermal_module.some_method();
res.render('view', {
title : 'Title',
data_to_vew: data
});
});
An object inside a "app.get" request stays always in memory regardless of is being accessed by a different user?
How to clean a "var" object after it runs?
How can I avoid this memory conflicts?
Do I have to code differently the module or call differently the module?
Thanks a lot.
UPDATE: I guess this is a proper solution but I need the review of some node.js/Express expert for approval it or correction.
app.js:
var ext_mod = require('./module');
var express = require('express');
var app = express();
app.get('/', function(req, res){
var ex_mod_instance = new ext_mod({});
ex_mod_instance.func_a({},function(ret){
res.send('Hello World: '+ret);
});
ex_mod_instance = null; // clean
});
app.listen(8080);
console.log('Listening on port 8080');
module.js:
var node_module = function(config) {
this.config = config;
this.counter=0;
};
node_module.prototype = {
func_a: function(param,done) {
this.counter++;
done(this.counter);
},
func_b: function(param,done) {
}
};
module.exports = node_module;
Is this the best way to save memory (leaks)?
Every time a function is called you do get "clean" local variables in the local scope. Modules are for the purpose of writing clean, organized code, so that you do not have every function and variable in the global scope. I believe require does cache the module, so maybe you are having a problem with variables in the closure around the function exported from the module. You'll have to include more code.
One way you could solve this is by exporting a function that creates the module. That function could be your constructor, which will scope your counter locally.
Again, this is one solution.
Your variable 'some_value' is global in the context of the module. So each time a request use this module, it uses the same variable.
(Require does cache the modules wich are loaded only the first time)
I can think of 2 ways to achieve this:
either you want one variable per request, and you declare this variable in the module function, or in the res.locals.some_value if you want to use it in many functions during the same request
either you want one variable per user, and then you need to use express session middleware, and add the variable to req.session.some_value

Resources