return value to app.js file in node js - 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());

Related

I get require is not defined error if I call it from external files

Hi,
I made an app for node.js so my app.js looks like this:
global.fs = require("fs");
global.vm = require('vm');
var includefile = function(path) {
var code = fs.readFileSync(path);
vm.runInThisContext(code, path);
}.bind(this);
includefile("variables.js");
as for variables.js I have this:
global.app = require("express")();
but when I start the app I get this error:
require is not defined at variables.js
why is it that requires loads fine if executed from app.js but not from an external file?
Thank you.
I'm a little confused, is variables.js just another source file in your project? All you should need to do is require the file in like you've done at the top. As an example for variables.js:
const Variables = {
fs: "some_value"
};
module.exports = Variables;
And for app.js
const { Variables } = require("./variables.js");
const fs = Variables.fs;
Executing console.log(fs); in app.js will print "some_value". Same can be done with functions.
If variables.js is part of your project code, you should use the answer of M. Gercz.
If it's not part of your project code and you want to get some information from it, you could use a json file:
app.js
const variables = require('variables.json');
console.log(variables.whatever);
variables.json
{ whatever: "valuable information" }
If it's not certain, that variables.json is preset, you can do a check using fs.existsSync;
Notice: As jfriend00 commented, using global is not recommended.

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 }.

Best way to invoke code inside a module in nodejs

From a performance perspective, is there any difference between invoking code by wrapping it in a function and then exporting it:
function doSomething () {
// doing something here
}
module.exports = doSomething();
And just requiring it without any exports? like this:
myModule.js
// Code doing something
file that requires the module:
var doSomething = require('./myModule');
And if the purpose of the code inside the module is to run just once, do I need to store it in a variable?
If you don't need the return value of that function, then you don't have to store it in a variable.
The difference with:
function doSomething () {
// doing something here
}
module.exports = doSomething();
and using:
var x = require('module');
var y = require('module');
vs.
function doSomething () {
// doing something here
}
module.exports = doSomething;
and using:
var x = require('module')();
var y = require('module')();
is that in the first case, the function will be run only once, while in the second case the function will be run twice.
The difference is that if you just include it without module.exports, then the code will execute immediately but be private to the module. You can only access the data if you export it somehow, with module.exports. It can be either a function or a Javascript Object. Essentially, you can view everything within the module as being completely hidden from everything else in your application.
The only shortcut that I know of is for JSON files. If you look here: Module.exports vs plain json for config files, you can see that you can require('file.json') and it will replace the contents of the json file with a Javascript object that you can then use in your application.

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
};

nodejs require statement issue

I'm new to nodejs. I have the following files and code:
// file: myfunc.js
function myfunc() { return "myfunc()"; }
exports = myfunc;
and
// file: index.js
var mf = require("./myfunc");
var mfunc = mf();
console.log(mfunc);
When I run node index.js from command line, I get the error
var mfunc = mf()
^
TypeError: Object is not a function
Why do I get this error? I saw someone else's code which I paste below and I tried to follow the same approach of trying to get require() to return a function instead of an object.
// file: index.js from another app
var express = require('express');
var app = express();
How come require('express') can return a function but require('./myfunc') can't return a function?
It should be...
module.exports = myfunc;
... instead. Quoting the doc:
If you want the root of your module's export to be a function (such as
a constructor) or if you want to export a complete object in one
assignment instead of building it one property at a time, assign it to
module.exports instead of exports.

Resources