本文介绍了node.js中app.js,index.js和server.js的约定?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在node.js中,似乎我遇到了相同的3个文件名来描述应用程序的主要入口点:

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


  • 何时使用 express-generator 包,将创建一个 app.js 文件作为主文件

  • 通过 npm init创建新的 package.json 文件时
  • code>,将提示输入主入口点文件。默认值为 index.js
  • 在我看到的某些程序中, server.js 也是主要入口点。

  • 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.

在其他时候,它们的用法似乎仍然存在细微的差异。例如,此节点应用程序目录结构在不同的上下文中使用 index.js server.js

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 <----------------------------

有什么区别,

推荐答案

即使有,也可以在任何三个文件名之间进行调用,即使调用任何文件,也有好处入口点index.js或server.js

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

为什么使用index.js:
发出 npm init 会将模块的主入口设置为index.js。有些人没有更改它,因此他们最终命名了其主要入口点index.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.

为什么选择server.js:
如果不使用您的节点程序包通过另一个程序包,而是一个独立的应用程序,则如果调用主入口点server.js,则可以发出 npm start 并启动您的应用程序。 npm start 将默认运行您的server.js文件。要更改此行为,请在package.json中提供 start 脚本。如果存在 start 脚本,则 npm start 将运行该脚本。

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 the 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只是一个约定-它的唯一优点是某些IDE(例如Visual Studio Code)将默认使用app.js作为调试程序的入口。这样,当使用最常见的框架Express创建一个app.js文件时,它就可以工作

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"

这篇关于node.js中app.js,index.js和server.js的约定?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 06:43