简体   繁体   中英

NodeJs setting up production and development

I was learning NodeJs advance concepts after going through the basic course.

I am following stepehen grinder course where we would be using his folliwng repo

I was initially walking through the repo where somethings were sort of new to me

My main question evolves around his index.js file in repo This isn't prime question but first he have done something like this

require('./routes/authRoutes')(app);
require('./routes/blogRoutes')(app);

Is this equivalent to something like this

const auth = require('./routes/auth.js') 
const profile = require("./routes/profile.js")
app.use('/auth', auth)
app.use('/profile', profile)

Second, Primary question , In his index.js file he have done something like this

if (['production'].includes(process.env.NODE_ENV)) {
  app.use(express.static('client/build'));

  const path = require('path');
  app.get('*', (req, res) => {
    res.sendFile(path.resolve('client', 'build', 'index.html'));
  });
}

This does not make sense to me at all, can someone explain me what does the above code do? and an interesting article which can help me comprehend.

Also, Can someone please tell me what does path module do? I went through their do documentation and was able to comprehend that path allows us to access files outside our node project. Is that correct understanding?

Concerning you first question:

It's not the same. app.use(...) defines a middleware that gets executed on all and every routes. Here, both routes files export a function which takes one argument: the application (ExpressJS server) instance. So, require('./routes/blogRoutes') gives you a function app => {...} , and by adding parenthesis and the app variable as a parameter you immediately execute this function with the current server (application) instance. Which in the end will create all the routes defined in the route file.

Concerning your second question:

The if is testing if the NODE_ENV variable is equal to production. If it is in production mode, app.use(express.static('client/build')); tells ExpressJS to serve static files from the client/build folder. The rest of the code app.get('*', ...) send the index.html file for calls made to any route except the one defined in the two routes files. The path.resolve only role is to easily build the absolute path of the index.html file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM