1

Hi,

I have an app on node.js which consists of a single file app.js that looks like this:

//variables
app = require("express")();
//many more variables here

//functions
function dosomething {}
//many more functions here

but since its getting a little too long I would like to break it into several files, one for variables only (variables.js) and another one for functions only (functions.js) and load them from app.js like this like when you do it with php

//variables
include(variables.js);

//functions
include(functions.js);

is it even possible to do that? Or I have to include everything in one single file like I do now?

Thank you.

Cain Nuke
  • 2,843
  • 5
  • 42
  • 65

3 Answers3

3

You can use Module.Export to export a separate file, and import it into another file using the require statement. Please check here for details:

https://www.geeksforgeeks.org/import-and-export-in-node-js/

Happy Learning :-)

  • 1
    so you have to add `module.exports = { name }` in each file you want to include into app.js? – Cain Nuke Jan 10 '22 at 18:21
  • Exactly that :) but without the Curly brackets, unless exporting multiple functions as an object. – NathanDoore Jan 10 '22 at 18:26
  • so if I only add `module.exports` it will automatically export all the functions inside the file? – Cain Nuke Jan 10 '22 at 18:29
  • You can wrap the whole file inside of a module.export like module.exports = { add: function (x, y) { return x + y; }, subtract: function (x, y) { return x - y; }, }; – NathanDoore Jan 10 '22 at 18:32
  • oh, sounds like its a lot more work than having everything just in a single file. – Cain Nuke Jan 10 '22 at 18:38
  • It is slightly more work, but it is a good habit to get into, as you will find 99% of projects split code like that. :) – NathanDoore Jan 10 '22 at 18:48
  • I cant get it to work for the variables file. I have only variables there and I added the line modules.export at the end but app.js still cant read them. – Cain Nuke Jan 10 '22 at 18:52
0

Importing API Endpoints

You can do this by using app.use(...) and point each endpoint to a specific file like so:

const express = require("express");

const app = express();

// User Functions
app.use("/api/user", require("./routes/api/user"));

//Orders functions
app.use("/api/orders/", require("./routes/api/orders"));


/**
 * Express Server Init
 */
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => console.log(`Server started on ${PORT}`));

Then in /routes/api/user/user.js you would have something like:

const express = require("express");
const router = express.Router();

router.post("/create", (req, res) => {
try {
    // Create user
} catch (error) {
    console.log(error);
    res.sendStatus(500);
}
});

module.exports = router;

Add and index.js inside /routes/api/user to point at the user file to keep things pretty when importing (otherwise you have to import it like /routes/api/user/user):

const user = require("./user");
module.exports = user;

Importing Single File

Not sure your use case but variables could be a bad naming convention since these values are more like constants than variables. Either way, you create it like this:

const variables = {
varibleOne: "valueOne",
varibleTwo: "valueTwo",
varibleThree: "valueThree",
};


module.exports = variables;

Then wherever you want to import it you can do:

const variables = require("./variables");

and access it like so variables.variableOneand so on.

Importing functions

You can also import different functions, say you need a file called helper.js where these are commonly functions needed all over you app, you could do something like this:

const twoDecimals = (number, decimal = ",") => {
let val = (Math.round(number * 100) / 100).toFixed(2);
return decimal === "." ? val : val.replace(".", decimal);
};

const getRandomInt = (max) => {
return Math.floor(Math.random() * Math.floor(max));
};

module.exports = { twoDecimals, getRandomInt };

Then wherever you needed you can import it by:

const { twoDecimals } = require("helper.js");

Now you have access to your helper functions anywhere.

Caio Mar
  • 2,344
  • 5
  • 31
  • 37
  • but what about a file I create myself? Like variables.js – Cain Nuke Jan 10 '22 at 18:46
  • I might have misunderstood your question, I thought you wanted to point different API endpoints to different file. If you are just importing a regular file, all you have to do is `const variables = require("./variables")` where you want to import it, and make sure you at the end of your variables file you add `module.exports = variables`. Makes sense? – Caio Mar Jan 10 '22 at 18:52
  • it does, except for one thing. In my variables.js file I have all my defined variables. in the line `module.exports =` I should list of all them? – Cain Nuke Jan 10 '22 at 18:57
  • I added to the answer, easier to see the formatting and solution. – Caio Mar Jan 10 '22 at 19:07
  • thanks, its clearer now although it seems like a lot of extra work and kinda makes me want to have everything in a single file as originally. – Cain Nuke Jan 10 '22 at 19:23
  • Good. Yeah, kinda depends on what your needs are. If your app is going to get more complex over time it's better to keep things organized now. If it's a simple and straight forward you might not need to split things up. For the sake of best practices I try to keep things clean but it's really up to you. – Caio Mar Jan 10 '22 at 19:26
  • @CainNuke Does [Node.js global variables](https://stackoverflow.com/q/5447771/1115360) help? – Andrew Morton Jan 10 '22 at 19:39
  • I ran into a few peoblems. For example when doing this: `const variables = { varibleOne: "valueOne", varibleTwo: "valueTwo", varibleThree: "valueThree" + varibleOne, };` it says that varibleOne is undefined despite I declared it above. Why is that? – Cain Nuke Jan 10 '22 at 20:05
  • You can't request a value inside of the object itself as you are declaring it, the compiler can't reference it because it doesn't exist yet. You could do something like `const a = 1; const b = 2; const variables = { total: a + b }` – Caio Mar Jan 10 '22 at 20:13
  • great, but what about cases like this: `const fs = require("fs"); const openfile = fs.readFileSync('file.txt');`? – Cain Nuke Jan 10 '22 at 21:53
  • What about it? You might want to consider taking a class on JavaScript because obviously you are missing the fundamentals of programming: variables, constants, functions... the basics, otherwise you're just gonna struggle all the way through it. – Caio Mar Jan 11 '22 at 01:27
0

You should get help from the JavaScript modular system (preferably COMMONJS). For example, suppose we have two files: 1-module.js 2-app.js So now let's create this files

module.js

let name = "hello world";
function printSomething(message) {
  console.log(message)
}
//here export all function and variable
module.exports.name = name;
module.exports.printSomething = printSomething

ok so Well now it is enough that "require" this file in main file :

main.js

// we 
const {name, printSomething} = require("./module.js");
printSomething(name);

for export all variable You need to create an object and specify your variables as a property:

let host = "localhost"
let dbname = "laravel_8"
let username = "root"
let password = "root"
function doSomething() {
 console.log("hello");
}
module.exports = {host, dbname, username, password, doSomething}

so in main file :

const variables = require("./module.js")
//host
let host = variables.host
//dbname
let dbname = variables.dbname
//function doSomething
let doSomething = variables.doSomething;
doSomething()
// or directly
variables.doSomething()

In fact, in php we use the "->" symbol to access properties, and in JavaScript we use "."

milad shiriyan
  • 296
  • 1
  • 9