How to use module.exports in expressJs? - javascript

So i was making this discord bot thing with discord js and i wanted to add some frontend to like change some things using website and not commands buut i cant or i just dont know how to
use module.exports in expressjs i tried some stuff like this
var server = website.listen(8080, function() {
var port = server.address().port;
console.log("Server started at http://localhost:%s", port);
});
and this
website.use('/vars.js', main)
but none of it works ;;-;
edit: I forgot to mention but "main" is module in vars.js
(code of vars.js)
module.exports = {
"token": process.env.DISCORDJS_BOT_TOKEN,
"creator": process.env.mainUserID,
"creatorPing": "<#" + process.env.mainUserID + ">",
"status": "Ay Bros",
"version": "2.0.7"
}
next edit:
I dont really want to export functions from this file but variables, bacause functions cant change my bot status, i want to be able to modify the variables so my bot will change its status :P

It depends how you want to export your main function. You can do it these ways:
Using default export/import
// vars.js
function main() {...}
module.exports = main;
// root file
const main = require('./vars.js');
website.use(main);
Using named export/import:
// vars.js
function main() {...}
module.exports = { main };
// root file
const { main } = require('./vars.js');
website.use(main);
Another problem you have is wrong usage of .use function. It should receive a function, not a filename. So you need to import function and then use it, as I did in examples.

It depends on how to export the function you want but almost developer follows this pattern to exports functions in nodejs.
function getUser() {
// Code here
}
function getUsers() {
// Code here
}
module.exports = {
getUser,
getUsers
}
This would output:
getUser: [Function: getUser], getUsers: [Function: getUsers] }
This gives us function names and documents the API clearly at the end of the file and this pattern name is revealing the module pattern.

Related

Export just a function from js file?

I have two modules one written in ts the other one in js. One of the utilities in js module need to be accessed in ts module.
So utility service.js as follows,
module.exports = {
helloFriends: function (message) {
console.log(message);
}
}
console.log('This part should not get invoked');
The called caller.ts as follows,
import { helloFriends } from './../moduleb/service';
helloFriends('Hello');
The output of above tsc caller.ts then node caller.js outputs following,
This part should not get invoked
Hello
I don't want any other code to get invoked from service.js except the function helloFriends, What can I do?
Note: Both modules are separate from each other with their own node dependencies.
Update:1
I handled with a hack, I defined IAM in both the modules .env files.
For service.js .env has IAM=service,
For caller.ts .env has IAM=caller,
So if service.js is called from its own module IAM is service but when it is called from outside e.g. from caller.ts it has IAM value as caller then in service.js I made following changes:
In service.js I made changes as follows:
var iam = process.env.IAM;
module.exports = {
helloFriends: function (message) {
console.log(message);
}
}
if (iam === 'service') {
console.log('This part should not get invoked, When called by external modules other than service');
}
So based on caller configuration I decide whether to execute a particular code section or not.
The plugin used for .env https://www.npmjs.com/package/dotenv
Update:2
Based on learnings I had after this question better approach would be to have functions to serve each purpose/functionality & export them individually.
I think the problem here is hinted at by this question: How does require() in node.js work?. In the question the asker has the following code in a module:
// mod.js
var a = 1;
this.b = 2;
exports.c = 3;
When mod.js is imported, the following properties are set:
// test.js
var mod = require('./mod.js');
console.log(mod.a); // undefined
console.log(mod.b); // 2
console.log(mod.c); // 3
The this/exports difference is interesting by itself, but it also tells us that the whole module is being run when it is required/imported and as it is stated in the answer you can even return part way through the module code.
This means that your console.log('This part should not get invoked'); will unfortunately be invoked unless you have a way of exiting the module code
Update:1
I handled with a hack, I defined IAM in both the modules .env files.
For service.js .env has IAM=service,
For caller.ts .env has IAM=caller,
So if service.js is called from its own module IAM is service but when it is called from outside e.g. from caller.ts it has IAM value as caller then in service.js I made following changes:
In service.js I made changes as follows:
var iam = process.env.IAM;
module.exports = {
helloFriends: function (message) {
console.log(message);
}
}
if (iam === 'service') {
console.log('This part should not get invoked, When called by external modules other than service');
}
So based on caller configuration I decide whether to execute a particular code section or not.
The plugin used for .env https://www.npmjs.com/package/dotenv
Update:2
Based on learnings I had after this question better approach would be to have functions to serve each purpose/functionality & export them individually.

How to reuse or factorize code?

I am currently writing a lot of Firebase Functions and some of them share the same variables and functions.
At the moment I copy paste them in each Firebase Functions file, as they are siloed, but I don't know what would be the best practice to share the code between them? For the variables a config file would be cool, for the code, a class all Functions could inherit too, but I'm not sure how to do it clean?
Organization: at the moment I have an index.js file that is referencing all Firebase Functions that I have. Each Firebase Functions is a JS file. That's the hierarchy I have, not optimal nor maintainable...
Examples
Variables:
I currently have to write the API key of Mailgun in all my Firebase
Function:
getThisProcessDone() that I currently copy in all my Firebase Functions
Anyone already had the thought? Thanks for your help!
For my Functions projects, I've been putting my reusable resources into functions/lib and requiring them normally as npm modules. I've also been separating out the code used in Functions from the definitions, which helps with testing.
For example, consider this structure:
functions/
|-index.js
|-newWidget.function.js
|-lib/
| |-Widget.js
test/
|-newWidget.functions.spec.js
Now if I want to declare a trigger to handle new widgets, I do something like the following:
// functions/index.js:
const functions = require('firebase-functions');
exports.processNewWidget = functions.https.onRequest(require('./newWidget.function.js').process);
// functions/newWidget.function.js
exports.process = function(req, res) {
res.send('Hello world!');
};
// test/newWidget.function.spec.js
// Note how we can easily test our widget processor separate from
// the third-party dependencies!
const newWidget = require('../functions/newWidget.function.js');
describe('newWidget', () => {
describe('process', () => {
it('should send hello world', function() {
const req = {};
cost res = { send: () => {} };
spyOn(res.send);
newWidget.process(req, res);
expect(res.send).toHaveBeenCalledWith('Hello world!');
});
});
});
And to include a class called Widget from inside newWidget.functions.js, I do something like this:
// functions/lib/Widget.js
class Widget {
constructor(name) { this.name = name; }
}
exports.Widget = Widget;
// functions/newWidget.function.js
class Widget = require('./lib/Widget').Widget;
exports.process = function(req, res) => {
const widget = new Widget(req.param.name);
res.send(widget.name);
};
Having your functions under a GitHub repo and calling them from master branch isn't an option? I am currently importing like this in package.json:
{
"name": "functions",
"description": "Cloud Functions for Firebase",
"dependencies": {
"cex-converter": "https://github.com/joaquinperaza/cex-converter/tarball/master"
},
"private": true
}
then you just require your conde dependency like require('cex-converter') and you get the last release of your dependency and doesn't need to modify anything to deploy your last release.

How to export an object with methods and properties

I have two js files in Electron (which uses Nodejs) and I try to export from one and require in another.
app.js:
App = {
server: {
host: '192.168.0.5',
user: 'root',
}
ping: function() {
}
}
exports.App = App
I have tried every way possible of exporting, including module.exports = App, module.exports.App = App and so on.
ping.js first attempt:
var App = require('../app.js') // I have also tried adding .App to the end
console.log(App) // This returns an object which contains the App object
ping.js second attempt:
var App = require('../app.js')
App.x = 'y'
console.log(App) // this returns an object which contains the App object and the x property
It may appear that App contains another App object, but console.log(App.App) says it doesn't exist.
The first thing I'd to do solve this would be to make sure I'm using the full path to the required module, as in:
const Path = require('path')
const App = require(Path.join(__dirname,'../app')) // the .js isn't needed here.
Note that this assumes that the app.js file is in the immediate parent directory of the one in which the application runs.
If that doesn't work, I'd make sure the files are where you think they are, and that the process you're running is located within the file system where you think it is. You can determine this by adding this to the top of your main script file:
console.log("current working directory:",process.cwd())
Or in es6:
console.log(`current working directory: %s`, process.cwd())
If the printed directory doesn't match your assumptions, modify your require statement accordingly.
And for the record, the "correct" way to export your App map would be to:
const App = {
...
}
module.exports = App
Or using es7:
export default App = {
...
}
(See export for more on es7 modules.)
Either way, you'd then require the module as:
const App = require(PATH_TO_APP)

unusual unexpected token in webpack

I have a file call scripts.js and it merely do var main = require('./main');
and my main.js is at the same level, it has
module.exports = {
console.log("hello");
}
I do webpack in my terminal I got unexpected token?
You can not include function executions into a javascript object (you are exporting an object), you need to export a function to achieve this
module.exports = function() {
console.log("hello");
}
And from your file where you require the export
var main = require('./main')(); // Add () to execute the function that you obtained
UPDATE:
You are executing console.log() in your main.js file, think that you can simply require some script without exporting nothing, and that file should be executed. For example you can put console.log("hello") without all the module.exports thing and the code should be executed, but when you check the value of your main variable (in the file where you do the require), you probably would not find anything useful.
You can also export a function(like in the code i send before) and then execute that function later, there's many ways to aproach this, I recommend you to google a bit about how module export works and how can you use it
You can check more about module.exports here https://www.sitepoint.com/understanding-module-exports-exports-node-js/, you are using it for the browser, but this examples for node should be usefull anyways

Nodejs: 'require' a module in Nodejs doesn't work with certain filename

Long-time user, first time asking a question.
I have a file (let's call it file.js) in which I'm attempting to require another file called user.service.js at the top of the file:
var userService = require('./user.service');
I'm quite sure that the path is correct and that the user.service.js file is exporting a populated object:
In user.service.js:
module.exports = {
signIn: signIn,
signUp: signUp,
updateProfile: updateProfile
};
However, userService is always an empty object {}. The odd thing is, if I recreate the file with another name in the same directory (e.g. user.service2.js), the require statement works properly. Or, if I rename file.js to something else, e.g. file2.js, the call works. Additionally, if I require the file inside a function within user.service.js, the statement works as well. However, I'd prefer to have the require statement at the top of the file and available to all functions inside it.
Thanks in advance for the help.
Edit:
Here's some sample code:
var userService = require('./user.service');
var testFunc = function () {
console.log(userService);
// this logs: {}
var userServiceInternal = require('./user.service');
console.log(userServiceInternal);
// This logs:
// {
// signIn: [Function],
// signUp: [Function],
// updateProfile: [Function]
// }
};
I figured it out...I had a circular dependency. Thanks for the comments!

Categories

Resources