node.js 使用 app.js 或“npm start”启动 Express.js?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32772292/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 19:19:36  来源:igfitidea点击:

Starting Express.js Using app.js or 'npm start'?

node.jsexpressnpm

提问by Mindsect Team

I've recently installed Node.js on a local server and when I create a 'server.js' file (adding a server using the .createServer() method), it loads fine.

我最近在本地服务器上安装了 Node.js,当我创建一个“server.js”文件(使用 .createServer() 方法添加一个服务器)时,它加载得很好。

However after installing Express.js, the default files are as follows:

但是安装Express.js后,默认文件如下:

/bin
/node_modules
/public
/routes
/views
app.js
package.json

After following some documentation, I am instructed to go to Terminal and enter the following command:

在遵循一些文档后,我被指示转到终端并输入以下命令:

node app.js

To which nothing happens, the command line refreshes to the next line in less than a second, and opening a browser after visiting the proper IP and port, to no avail.

对此什么也没发生,命令行不到一秒刷新到下一行,访问正确的IP和端口后打开浏览器,无济于事。

Below is the code inside of the app.js file:

下面是 app.js 文件中的代码:

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var routes = require('./routes/index');
var users = require('./routes/users');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', routes);
app.use('/users', users);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
  app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
      message: err.message,
      error: err
    });
  });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  res.render('error', {
        message: err.message,
        error: {}
      });
    });

module.exports = app;

I understand that the actual 'express' module that is being required in the beginning of the file is where the magic happens, however, when I run the command line:

我知道文件开头需要的实际“express”模块是神奇发生的地方,但是,当我运行命令行时:

node app.js

Nothing happens. However, if I call the following line:

没发生什么事。但是,如果我调用以下行:

npm start

Everything appears to be okay. I would like to follow the documentation as is, any reason why the app.js wouldn't be working?

一切似乎都没问题。我想按原样遵循文档,app.js 无法正常工作的任何原因?

Thank you.

谢谢你。

UPDATE: My question was too similar to another one already posted, so I must clarify exactly how they were different. In the other question, a person was questioning a code number they received while running the Supervisor command on the default 'app.js' file.

更新:我的问题与已经发布的另一个问题太相似了,所以我必须明确说明它们的不同之处。在另一个问题中,有人质疑他们在默认“app.js”文件上运行 Supervisor 命令时收到的代码。

While similar in nature, this question should remain, as those who are confused by using my same approach will focus on the identity of the actual 'app.js' file by using 'node app.js' without having full knowledge of the Supervisor utility.

虽然本质上相似,但这个问题应该仍然存在,因为那些对使用我的相同方法感到困惑的人将通过使用“node app.js”来关注实际“app.js”文件的身份,而无需完全了解 Supervisor 实用程序.

Regards.

问候。

回答by Mindsect Team

Thank you all for your great responses, as they really allowed me to understand what is actually going on with the app.js file and where it receives it's functionality. Thank you to both Matthew Bakaitis and Bjarni Leifsson for their great input.

感谢大家的精彩回复,因为他们真的让我了解 app.js 文件的实际情况以及它在哪里接收它的功能。感谢 Matthew Bakaitis 和 Bjarni Leifsson 的大力投入。

The only reason why I am going to go ahead and answer my own question is because while the nature of the app.js file was explained, exactly how to replicate calling the 'node app.js' command from the command line as to replicate a Node.js book that I was following wasn't implicitly addressed.

我要继续回答我自己的问题的唯一原因是,虽然解释了 app.js 文件的性质,但究竟如何从命令行复制调用“node app.js”命令以复制一个我所关注的 Node.js 书籍并没有被隐含地提及。

After searching google with the specific phrase "app.js in previous express.js versions", I happened upon a great article by Jilles Soeters entitled "Understanding the Express app.js":

在使用特定短语“以前 express.js 版本中的 app.js”搜索谷歌后,我偶然发现了 Jiles Soeters 的一篇题为“了解 Express app.js”的精彩文章:

http://jilles.me/getting-the-express-app-js/

http://jiles.me/getting-the-express-app-js/

Below is the excerpt of the solution that worked for me:

以下是对我有用的解决方案的摘录:

The file I'm covering is app.js, the main configuration file for your Express app. When I first opened app.js it confused me. I will save you the trouble of doing research and just cover them here.

Before you do anything add the following to your app.js

我要介绍的文件是 app.js,它是 Express 应用程序的主要配置文件。当我第一次打开 app.js 时,它让我很困惑。我会省去你做研究的麻烦,我会在这里介绍它们。

在你做任何事情之前,将以下内容添加到你的 app.js 中

app.listen(3000);

You need that in order to be able to actual open your app in the browser. Go to 127.0.0.1:3000after you've started your app (using node app.js)

您需要它才能在浏览器中实际打开您的应用程序。启动应用程序后转到127.0.0.1:3000(使用 node app.js)

After doing this, I was able to run the command

这样做后,我能够运行命令

node app.js

I was able to run this command from the root directory of the Express install and proceed with my Node.js book with no additional problems.

我能够从 Express 安装的根目录运行这个命令,并继续我的 Node.js 书,没有其他问题。

回答by Matthew Bakaitis

This is a common problem that is caused when tutorials don't clearly explain what express is doing when it generates an app. You're trying to learn the new tech, but the tutorial is actively working against you. :(

这是一个常见的问题,当教程没有清楚地解释 express 在生成应用程序时在做什么时会导致。您正在尝试学习新技术,但本教程对您不利。:(

The answer:

答案:

When you use the generator, package.jsonis configured so that npm start calls ./bin/www.

使用生成器时,package.json配置为 npm start 调用./bin/www.

Thatfile includes app.jsand after the include, calls app.listen.

文件包含app.js并在包含之后调用app.listen.

app.jsdoesn'tcall app.listenwhich is why if you call it directly, it exits with no code or info. You've got to call ./bin/wwwor you have to modify app.js...which then defeats some of the reasons you'd use a generator.

app.js调用app.listen,这就是为什么如果你直接调用它,它会在没有代码或信息的情况下退出。你必须打电话./bin/www或者你必须修改app.js......然后打败了你使用生成器的一些原因。

A related questionhere on the site saw a similar problem when trying to use supervisorto keep an app running but kept getting an exit 0result.

网站上的一个相关问题在尝试使用supervisor以保持应用程序运行但一直得到exit 0结果时看到了类似的问题。

回答by Bjarni Leifsson

How I understand this, and I have just started to use node.

我是如何理解这一点的,我刚刚开始使用 node.js。

There is a bin folder with www in it. There all the magic happens. So when you do node app.js it gets executed but the logic to the everything is in bin/www

有一个带有 www 的 bin 文件夹。所有的魔法都在那里发生。因此,当您执行 node app.js 时,它会被执行,但所有内容的逻辑都在 bin/www 中

So if you look into package.json you see this init :

所以如果你查看 package.json 你会看到这个 init :

"scripts": { "start": "node ./bin/www" },

"scripts": { "start": "node ./bin/www" },

So giving that, you see to execute the script you use the start method and it is linked to ./bin/www

因此,您会看到执行使用 start 方法的脚本并将其链接到 ./bin/www

If you take a look in that file you will find out that the whole logic of the server to start up is in there.

如果您查看该文件,您会发现启动服务器的整个逻辑都在其中。

So if you change start to something else, like TurnOn and would do npm TurnOn, it will execute ./bin/www and the whole project for you.

因此,如果您将 start 更改为其他内容,例如 TurnOn 并执行 npm TurnOn,它将为您执行 ./bin/www 和整个项目。

The structor of the project is all linked together, and app.js is not enough to start the server.

项目的structor都是链接在一起的,app.js还不足以启动服务器。

Hope this helps.

希望这可以帮助。

回答by Nadav

When using Express the Express instance will create the server for you. Typically your app/index/server.js file will begin with these lines:

使用 Express 时,Express 实例将为您创建服务器。通常,您的 app/index/server.js 文件将以以下几行开头:

const express = require('express');
const app = express();

These lines require Express and then instantiate an instance of Express within the app variable. Express then uses var server = http.createServer(app);to start a server for you. All you need to do is to make sure your app listens to that server (as you wrote). However, the port for the connection may vary so it is not advisable to hard-code it. Instead it should be retrieved from the app variable as such:

这些行需要 Express,然后在 app 变量中实例化 Express 的一个实例。Express 然后用于var server = http.createServer(app);为您启动服务器。您需要做的就是确保您的应用程序侦听该服务器(如您所写)。但是,连接的端口可能会有所不同,因此不建议对其进行硬编码。相反,它应该从 app 变量中检索,如下所示:

app.listen(app.get('port'), function(){
    //Something to do when the server starts.
});

Additionally, after creating your own app.js file make sure to change your package.json file to start the app via app.js instead of the Express module. By default your package.json might look like this:

此外,在创建您自己的 app.js 文件后,请确保更改您的 package.json 文件以通过 app.js 而不是 Express 模块启动应用程序。默认情况下,您的 package.json 可能如下所示:

"scripts": {
 "start": "node ./bin/www"
},

But after you created your own app/index/server.js file you want node to start running that file on startup instead:

但是在您创建自己的 app/index/server.js 文件后,您希望节点在启动时开始运行该文件:

"scripts": {
 "start": "node app.js"
}

You can then start your app by writing npm startfrom the project directory.

然后,您可以通过npm start从项目目录写入来启动您的应用程序。