nodejs require statement issue - node.js

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.

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.

In Node, why does 'require' assignment sometimes require curly brackets?

Running some tests through Chai, I noticed the tests would fail under this code:
const add = require('./addition');
//'add is not a function error' even though it's directly exported as a function
But it would pass under this:
const {add} = require('./addition');
Yet when using npm modules, everything is declared without the brackets:
var express = require('express');
var app = express();
var session = require('express-session');
And those are essentially objects with multiple properties to be accessed. Why does it work this way? Is it only function exports that must be assigned as objects explicitly?
This is known as object destructuring. Please refer the link.
For example you have exported a file called sampleFunctions.js which has following functions as exports
function function1(params) {};
function function2(params) {};
module.exports = {
sampleFunc1: function1,
sampleFunc2: function2
}
Now when you need to require it, there are two ways -
when you only need one function(using object destructuring)
let {sampleFunc1} = require('./sampleFunctions');
sampleFunc1();
In this you exposed only the required function not all of the functions exported from that file.
when you want to require all the functions from that file
let sampleFuncs = require('./sampleFunctions');
let samFunc1 = sampleFuncs.sampleFunc1;
samFunc1()

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());

Import Export Module in nodejs

In Nodejs, i created a function in th path /js
var myfunction=function(param1){
}
exports.myfunctionA=myfunctionA
In the path routes, I want call this function
myfunctionA=require('./js/myFunctionA')
But I have a message:
Unhandled rejection TypeError: myfunctionA is not a function
Thanks for your help,
Mdouke
You have typo in function name
var myfunctionA=function(param1){}
exports.myfunctionA=myfunctionA
If this file is named functionA.js then You can include a module by
var moduleA = require('./js/functionA')
In this module You have a functionA. You can access to this function by
var functionA = moduleA.functionA
or simpliest way
var functionA = require('./js/moduleA').functionA
If you module only export a one function, then named this file functionA.js and write
exports = function(){}
and access to this function by
functionA = require('./js/functionA')
I hope I help.
you can modify the content of your file in js path as follow
exports.myfunctionA = function(param1){
}
after that in route path, you require:
var myfunction = require('./js/myFunctionA');
and use it:
myfunction.myfunctionA();

exporting console.log from a module in node.js

I'm using a customized version of node-clim, but I want to put away all the customization code in a module of its own and require() it in my main app. But I can't seem to do that..
This code works
var util = require('util');
var clim = require('clim')
clim.logWrite = function(level, prefixes, msg) {
...
customizing code
...
process.stderr.write(...);
};
var console = clim();
console.log('hey'); // works
But in trying to put the above in a separate file clim.js and exporting the console object...
module.export = console;
and require()ing it in my main app doesn't work..
var console = require('./clim');
console.log('hey');
// ^ TypeError: Object #<Object> has no method 'log'
What am I doing wrong?
Change
module.export = console;
to
module.exports = console;

Resources