Require express in one file and use express.static in another - javascript

How would I use express in one file, in other files that need to use the express package also. Currently I have a file server.js, that has the
var express = require('express');
var app = express();
I want to use express in my other files that are in different directories, how would I do this without doing a require?
Updated question
How would I pass 'var express = require('express');' to another file so that I can use express.static?

If you don't want to use require you can pass app like this:
app.js
var express = require('express');
var app = express();
var something = require('./something')(app);
something.js
module.exports = function (app) {
// do something with app
};

You can use module.exports to assign app variable , which can be used imported/required my other file . Sample example like below
a.js
var express = require('express');
var app = express();
module.exports.app = app;
b.js
var a = require('./a');
a.app.listen(3000,function(){
console.log("Server Is up and running");
});

In nodeJs different files that we have in our application are treated as different module, so when we want to use them we export them and use them, here express is a package we are using so you can define it one file and export that file and require it in another file.
use module.exports and require it another file.

Related

Why not using "require('express')()"

To create a simple Web server with NodeJS and Express, all the tutorials giving examples like this
const express = require('express');
const app = express();
app.listen(3000, () => console.log("Started"))
app.get('/', (req, res) =>{
res.send("Yaaa")
})
My question is, Why not write it like this?
const app = require('express')();
app.listen(3000, () => console.log("Started"))
app.get('/', (req, res) =>{
res.send("Yaaa")
})
The only difference is merging lines 1 and 2, as far as I'm not going to use/need the "express" constant anymore.
Is that wrong? And why?
As far as I know about express framework. Express exposes us to a lot of useful functions. If we don't require or import express in our application then, Our application will not be able to use those functions.
For example if you are creating some REST APIs then, We need our APIs to take form-data or raw as input. If we want to allow our application to take raw-json as input then, we need to add a middleware which consumes a built-in express function.
app.use(express.json())
If you want create an application that has a seperate folder for all the routes. Then, we use express.Routes() for that. That's how we create routes file in seperate routes folder:
import express from 'express';
import userController from 'path/to/user/controller';
const router = express.Router();
router.post('/follow/:userid/:following', helper.verifyToken, userController.follow);
router.get('/someRoute', userController.someAction);
export default router;
Similarly, If we want to serve some static HTML or some react-build. Then, we use express.static() inside app.use() middleware like this:
app.use(express.static('/path/to/static/folder'));
As long as you don't need access to the express module elsewhere in this file, then doing:
const app = require('express')();
is the best way.
But if we require to use to this express module again and again. Such as below
const app = require('express')();
const friendsRouter = require('express').Router();
Then it becomes a problem and you have require it again and again.
So to make our code less redundant, we use normal given approach. As in below code:
const express = require('express');
const app = express();
const friendRouter = express.Router();

How to app.use() a file that has some other app.use() within nodeJS

So maybe it sounds pretty tricky at a first look.I'll explain what I actually want to do :
I'm working with NodeJS & expressJS and I'm trying to modularize the project,here is what I want to do:
Let's say I have the in the main server .js file the router.get / post / put / delete etc splitted in some other files for every type :
Ex :
...
app.use(require('./routes/account_method1.js'));
app.use(require('./routes/account_method2.js'));
app.use(require('./routes/games_method1.js'));
app.use(require('./routes/games_method3.js'));
app.use(require('./routes/emails_method5.js'));
...
I performed that pretty easy : I just used the code mentioned above in the main .js file and in the required files I've just put :
module.exports = router;
And that's pretty much it.But the problem is :
Now I want do to something like :
...
app.use(require('./routes/account/panel.js'));
app.use(require('./routes/games/panel.js'));
app.use(require('./routes/emails/panel.js'));
...
And in every ./routes/x/panel.js file to have the specific .js files required withing , for just an example in ./routes/account.panel.js I would like to have and work :
app.use(require('./account_method1.js'));
app.use(require('./account_method2.js'));
Assuming account_method1.js and account_method2.js are in the same directory with the specific panel.js file.And then,require these panel.js files in the main server .js file.
So if now I have :
Server ---> ./routes/account_method1.js
---> ./routes/account_method2.js
I would want to make it :
Server ---> ./routes/account/panel.js ---> ./routes/account_method1.js
./routes/account_method2.js
I won't paste here any code because it's just a problem about a way of importing files and I've already mentioned how I require my .js files on the main server.
Soo...what do you think?
EDIT :
I think will show you where is the problem :
./routes/test.js ( this file have to add to app another file,register.js)
const express = require('express');
const router = express.Router();
console.log("BEFORE ROUTER.USE");
router.use(require('./register.js'));
console.log("AFTER ROUTER.USE");
module.exports = router;
./app.js (the main .js server file)
....
var test = require('./routes/test.js');
app.use(test);
....
./routes/register.js
const express = require('express');
const router = express.Router();
...
//some router.post / get / delete
...
module.exports = router;
And when I try to access the URLs from that register.js file they aren't working
Better way is using router:
eg: controller/api.js
const express = require('express')
const router = express.Router()
router.get('/', function(req, res) {
//console.log(res.apiData);
res.json({message:'ok'});
});
module.exports = router;
and later
app.use('/api', require('controller/api'))
Router can be imported to another router. I'm use this:
main.js:
app.use(require('./controller'));
controller/index.js:
const express = require('express')
const router = express.Router()
const isAuth = require('../middlewares/is-auth')
const isValidApiKey = require('../middlewares/is-api-key')
const isAdmin = require('../middlewares/is-admin')
router.use('/auth', require('./auth'));
router.use('/profile', isAuth, require('./profile'));
router.use('/api', isValidApiKey, require('./api'));
router.use('/admin', isAuth, isAdmin, require('./admin'))
If the request service code is long, you can also move it to a separate file, but I think it's better to divide it into smaller, reusable parts and use it as middleware, eg:
route.all('/:orderId(\\d+)', fileOrderMiddleware, fileAltMiddleware, hasTransferMiddleware, orderServeMiddleware);

nodejs how to execute other js file from index.js?

I want to create web app with nodejs but with structure like this
- modules
| - module1
| - module1.js
| - module2
| - module2.js
- index.js
- settings.js
First, i never use nodejs from scratch
Second, i know you will suggest using any other framework, sorry guys here i want to understand how nodejs and may be other nodejs framework works.
Third, this is for educational purpose
in modules/module1/module1.js :
res.setHeader('Content-Type', 'text/plain; charset=utf-8')
res.end('Hello World aw!')
honestly i dont know how to code it properly, what i really want is i wanna execute that code and response to browser Hello World aw! from index.js :
router.get('/', function (req, res) {
//in here i call modules/module1/module1.js, and execute the code
})
and how to do that properly? so it can run well
to load any script or module in nodejs you need to use require
like this
var module1 = require(__dirname + 'modules/module1/module1.js');
and then you can use module1 anywhere in your code
BTW for express you should create routes and then attach that routes to your app. See example below.
users.js
var express = require('express');
var router = express.Router();
/* GET users listing. */
router.get('/', function(req, res, next) {
res.send('respond with a resource');
});
module.exports = router;
server.js
var express = require('express');
var app = express();
var users = require('./routes/users');
....
app.use('/users', users);
Every time with node when you need to have a module in a particular page you need to require this module.
example: you want to get the library express so at the top of your file who you want this library you do something like that.
var express = require('express');
Now you can use express in all the file. When this is a node library you just need to require the name.
this is the same thing with a file you create and you want inside a other one
var myfile = require('./../myfile');
with that you can use the word myfile inside all the file. But you need to figure out the path to this one.
A good links for read about this

What's the best way to access the express 'app' object from inside a separate route file?

In Express 4, by default, routes are loaded from a separate file:
app.use('/', routes);
Would load routes/index.js.
I have a third-party library that attaches to app itself. Is there a preferred way to access app from inside routes/index.js?
I've thought about dependency injection ie, routes/index.js does
module.exports = function(app){
(routes go here)
}
and then:
app.use('/', routes(app))
But I wonder if there's a better way. What's the best way to access the express 'app' object from inside a separate route file?
You can simply access app by req.app in your route handlers
I looked at a number of app generators and everyone does it differently.
Mostly though I've seen it work the opposite from what you are asking. The route modules do not get the app passed in, they just return themselves and are attached to the app.
I like to use the following pattern:
routers/hello.js:
var express = require('express');
var router = express.Router();
router.get('/hello', function (req, res) {
res.send('Hello, World!');
});
module.exports = router;
app.js:
var express = require('express');
var app = express();
app.use('/sample', require('./routers/hello'));
// other routers are attached
module.exports = app;
server.js:
var http = require('http');
var app = require('app');
var server = http.createServer(app);
server.listen(3000):
So the modules in routers/ return an Express Router object that are then attached to the app on their respective paths (routes).
This is inspired on the Express Application generator, but uses Routes instead of Routers. My advice, use the linked generator and start from there.

Node.js and dependecies management

Here is what i'm concerned about:
I'm writing a webapp in Node.js using express 4.
The question is for managing dependecies in all the code, but let me show you an example. I'm managing dependencies like this:
server.js:
var express = require('express');
var app = express();
app.use('/auth', require('./routes/auth'));
app.use('/profile', require('./routes/profile'));
routes/auth.js:
var express = require('express');
var router = express.Router();
// add routes to router
module.exports = router;
routes/profile.js:
var express = require('express');
var router = express.Router();
// add routes to router
module.exports = router;
How you can see, i'm importing express every time i need it in every module. I'm showing you the example with express, but i'm doing it with others modules.
Makes it better if i manage dependencies like this?
server.js:
var express = require('express');
var app = express();
app.use('/auth', require('./routes/auth')(express));
app.use('/profile', require('./routes/profile')(express));
routes/auth.js:
module.exports = function (express) {
router = express.Router();
// add routes to router
return router;
}
routes/profile.js:
module.exports = function (express) {
router = express.Router();
// add routes to router
return router;
}
I have to admit that my doubts are due to my lack of knowledge about Javascript and Node.js and my background with Python, where we do like the first form.
Any advice would be appreciated.
There is no real difference in performance, since Node.js' require caches every module on first call. However, the second approach has the benefits of explicit dependency injection, i.E. you could test every module in higher isolation by providing a mocked version of express. Plus you are ready for providing further dependencies like configuration or database objects.

Categories