Requiring a folder and using exports.{function} - node.js

Currently I have this setup:
// index.js
var example = require('./folder');
and:
// folder/index.js
require('./more');
// folder/test.js
exports.thing = function() {
console.log('test');
return true;
}
But when I try in index.js to call example.thing I get:
example.thing is not a function
Is there any way to make it work? Cheers.

Directory requiring is not supported by node. It requires index.js if it presented in the directory.
To export thing in index.js do the following:
// index.js
exports.thing = require('./test.js').thing;

Are you calling it right? Because I tried it and it's working.
You should call it like example.thing() and not example.thing.

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.

When first require() invoked, Does node js do caching? With Next.js

// FILE A.js
let users;
class A () {
static init() {
users = 'abc';
}
static addSomething () {
return users.slice(1);
}
}
module.exports = A;
// FILE A_1.js
const A = require('./A');
A.init();
// FILE A_2.js
const A = require('./A');
A.addSomething();
When I invoke A_2.js file, It throws error Can't call slice on undefined.
I heard something like when first require fired, it's cached.
I re-write module.exports = A to module.exports.default = A;
And const A = require().default;
It doesn't work like before.
What am I missing?
Thank you.
Sorry for the pseudocode on question.
It was split with next.js API dir, and custom model dir.
I found the information.
https://www.reddit.com/r/nextjs/comments/eiykfc/share_database_connection_in_nextjs_api_routes/
It looks like next.js serverless philosophy it's self.
This won't work when Next.js splits each API route into its own bundle with Webpack, will it? For me it did not cache modules between API routes, at least in development mode.

fs.writeFileSync function doesn't write to file when included as a module

Consider the following:
conversations.json : []
db.js :
let fs = require('fs');
let conversations = require('./conversations.json');
function addConversation(conversation){
console.log(conversations);
conversations.push(conversation);
try{
fs.writeFileSync('conversations.json', JSON.stringify(conversations));
}
catch(err){
console.error('Parse/WriteFile Error', err)
}
}
module.exports = {
addConversation
}
app.js :
let database = require('./db.js');
database.addConversation(
{
key1: '1233',
key2: '433',
key3: '33211'
}
);
Running:
node app.js
No error is being raised. Everything compiled as expected. The problem is that the conversations.json isn't being updated once the addConversation function is called from app.js.
What's interesting is that once the addConversation is called within the db.js everything works great and the conversations.json is being updated.
What am I missing?
What am I missing?
Probably when loading as a module, you're writing the file to the wrong directory.
When you do this:
fs.writeFileSync('conversations.json', JSON.stringify(conversations));
That writes conversations.json to the current working directory which may or may not be your module directory. If you want it written to your module directory which is where this:
let conversations = require('./conversations.json');
will read it from, then you need to use __dirname to manufacture the appropriate path.
fs.writeFileSync(path.join(__dirname, 'conversations.json'), JSON.stringify(conversations));
require() automatically looks in the current module's directory when you use ./filename, but fs.writeFileSync() uses the current working directory, not your module's directory.

What is exports.install in node js?

Hi I found a framework where they use a lot this pattern.
exports.install = function(){
//code
}
but usually you see this pattern in nodejs
module.exports = {
//code
}
Is this the same thing or is this something else ?
exports is the object corresponding to module.exports before you do anything to it. I think it's due to some legacy code, but basically folks use module.exports if they want to replace the whole object with their own object or a function, while they use exports if they just want to hang functions off the module. It's a little confusing at first, but essentially exports.install just means that calling code would do something like:
const mod = require('that-module');
mod.install(params, callback); // call that function
The framework you're looking at is probably using it as part of a bootstrapping process, afaik it doesn't have significance to the node engine itself.
Yes, it is the same thing. You can use one of 2 ways to setup your code.
The different thing is memory. They point to same memory. You can think exports like a variable and you can not use this way to export your module:
Given this module:
// test.js
exports = {
// you can not use this way to export module.
// because at this time, `exports` points to another memory region
// and it did not lie on same memory with `module.exports`
sayHello: function() {
console.log("Hello !");
}
}
The following code will get the error: TypeError: test.sayHello is not a function
// app.js
var test = require("./test");
test.sayHello();
// You will get TypeError: test.sayHello is not a function
The correct way you must use module.exports to export your module:
// test.js
module.exports = {
// you can not use this way to export module.
sayHello: function() {
console.log("Hello !");
}
}
// app.js
var test = require("./test");
test.sayHello();
// Console prints: Hello !
So, it just is style of developer.

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

Resources