2

Hi I'm new to nodeJs and currently developing a Rest API using node.I'm planning to develop it with a good folder structure, so I can scale it up easily. There I'm using several route files according to the business logic.

ex :- authRoutes,profileRoutes,orderRoutes ......

Currently in every single route file I had to include following codes

var express    = require('express');
var router = express.Router();
var jwt = require('jsonwebtoken');
var passport = require('passport');

My problem is , Is it totally fine to use above code segments in all the route files( I'm concerning about the code optimisation/coding standards and execution speed ) or is there any better way to do this.

It's better if you can explain the functionality of require() function.

Thanks

Achira Shamal
  • 527
  • 1
  • 5
  • 18

1 Answers1

0

In my experience, this is very standard to do. I suggest reading this question and answer to learn more about the way it affects the speed of your programs.

TL;DR of require()

When your lines of code are ran that include a variable that exists because of a require(), for instance

var https = require('https');
https.get(url, function(response) {...});

The compiler reads it and goes into the https module folder, and looks for the .get function.

However, if you are trying to require() a certain JavaScript file, such as analysis.js, you must navigate to that file from the file you are currently in. For instance, if the file you want is on the same level as the file you are in, you can access it like this:

var analysis = require('./analysis.js');
//Let analysis have a function called analyzeWeather
analysis.analyzeWeather(weather_data);

These lines of code are a little different from above. In this require() statement, we are saying grab the .js file with this name, analysis. Once you require it, you can access any public function inside of that analysis.js file.

Edits

  • Added require() example for .js file.
notphilphil
  • 385
  • 5
  • 16