Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
309 views
in Technique[技术] by (71.8m points)

Conventions for app.js, index.js, and server.js in node.js?

In node.js, it seems I run into the same 3 filenames to describe the main entry point to an app:

  • When using the express-generator package, an app.js file is created as the main entry point for the resulting app.
  • When creating a new package.json file via npm init, one is prompted for the main entry point file. The default is given as index.js.
  • In some programs I have seen, server.js serves as the main entry point as well.

Other times, still, it seems as though there are subtle differences in their usage. For example, this node app directory structure uses index.js and server.js in different contexts:

app
  |- modules
  |    |- moduleA
  |    |    |- controllers
  |    |    |    |- controllerA.js
  |    |    |    +- controllerB.js
  |    |    |- services
  |    |    |    +- someService.js
  |    |    +- index.js <--------------
  |    +- index.js <-------------------
  |- middleware.js
  +- index.js <------------------------
config
  +- index.js <------------------------
web
  |- css
  |- js
server.js <----------------------------

What are the differences, if any, between these three names?

question from:https://stackoverflow.com/questions/36002413/conventions-for-app-js-index-js-and-server-js-in-node-js

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Even though you can call the files anything you want, there's an advantage to calling the entry point index.js or server.js

Why index.js: When you issue npm init it will set the main entry point of the module to index.js. Some people don't change it, so they end up naming their main entry point index.js. It means there's one less thing to do.

Why server.js: If your node package is not going to be consumed by another package, but rather is a stand-alone app, then if you call your main entry point server.js, then you can issue npm start and start your app. npm start will run your server.js file by default. To change this behavior, supply a start script in package.json. If a start script exists, npm start will run that script instead.

app.js is just a convention -- the only advantage to it is that some IDEs, such as Visual Studio Code will default to app.js as the entry point of a program you debug. That way when using the most common framework, Express, which creates an app.js file, "it just works"


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...