简体   繁体   English

Node.js中的process.env.PORT是什么?

[英]What is process.env.PORT in Node.js?

what is process.env.PORT || 3000什么是process.env.PORT || 3000 process.env.PORT || 3000 used for in Node.js? process.env.PORT || 3000用于Node.js? I saw this somewhere:我在某处看到了这个:

 app.set('port', process.env.PORT || 3000);

If it is used to set 3000 as the listening port, can I use this instead?如果用来设置3000为监听端口,可以用这个代替吗?

app.listen(3000);

If not why?如果不是为什么?

In many environments (eg Heroku), and as a convention, you can set the environment variable PORT to tell your web server what port to listen on.在许多环境(例如 Heroku)中,作为惯例,您可以设置环境变量PORT来告诉您的 Web 服务器要侦听的端口。

So process.env.PORT || 3000所以process.env.PORT || 3000 process.env.PORT || 3000 means: whatever is in the environment variable PORT, or 3000 if there's nothing there. process.env.PORT || 3000表示:环境变量 PORT 中的任何内容,如果那里什么都没有,则为 3000。

So you pass that to app.listen , or to app.set('port', ...) , and that makes your server able to accept a "what port to listen on" parameter from the environment.因此,您将其传递给app.listenapp.set('port', ...) ,这使您的服务器能够接受来自环境的“监听哪个端口”参数。

If you pass 3000 hard-coded to app.listen() , you're always listening on port 3000, which might be just for you, or not, depending on your requirements and the requirements of the environment in which you're running your server.如果您将3000硬编码传递给app.listen() ,则您始终在侦听端口 3000,这可能只适合您,也可能不适合您,具体取决于您的要求和运行您的环境的要求服务器。

  • if you run node index.js ,Node will use 3000如果你运行node index.js ,Node 将使用3000

  • If you run PORT=4444 node index.js , Node will use process.env.PORT which equals to 4444 in this example.如果您运行PORT=4444 node index.js ,Node 将使用process.env.PORT ,在本例中等于4444 Run with sudo for ports below 1024.对 1024 以下的端口使用sudo运行。

When hosting your application on another service (like Heroku, Nodejitsu, and AWS), your host may independently configure the process.env.PORT variable for you;当在其他服务(如 Heroku、Nodejitsu 和 AWS)上托管您的应用程序时,您的主机可能会为您独立配置process.env.PORT变量; after all, your script runs in their environment.毕竟,您的脚本在他们的环境中运行。

Amazon's Elastic Beanstalk does this.亚马逊的 Elastic Beanstalk 可以做到这一点。 If you try to set a static port value like 3000 instead of process.env.PORT || 3000如果您尝试设置静态端口值,例如3000而不是process.env.PORT || 3000 process.env.PORT || 3000 where 3000 is your static setting, then your application will result in a 500 gateway error because Amazon is configuring the port for you. process.env.PORT || 3000其中 3000 是您的静态设置,那么您的应用程序将导致 500 网关错误,因为 Amazon 正在为您配置端口。

This is a minimal Express application that will deploy on Amazon's Elastic Beanstalk:这是一个将部署在 Amazon 的 Elastic Beanstalk 上的最小 Express 应用程序:

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

app.get('/', function (req, res) {
  res.send('Hello World!');
});

// use port 3000 unless there exists a preconfigured port
var port = process.env.PORT || 3000;

app.listen(port);

In some scenarios, port can only be designated by the environment and is saved in a user environment variable.在某些场景中, port只能由环境指定,并保存在用户环境变量中。 Below is how node.js apps work with it.下面是 node.js 应用程序如何使用它。

The process object is a global that provides information about, and control over, the current Node.js process. process对象是一个全局对象,它提供有关当前 Node.js 进程的信息并对其进行控制。 As a global, it is always available to Node.js applications without using require() .作为全局变量,它始终可用于 Node.js 应用程序,而无需使用require()

The process.env property returns an object containing the user environment. process.env属性返回一个包含用户环境的对象。

An example of this object looks like:此对象的示例如下所示:

{
  TERM: 'xterm-256color',
  SHELL: '/usr/local/bin/bash',
  USER: 'maciej',
  PATH: '~/.bin/:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin',
  PWD: '/Users/maciej',
  EDITOR: 'vim',
  SHLVL: '1',
  HOME: '/Users/maciej',
  LOGNAME: 'maciej',
  _: '/usr/local/bin/node'
}

For example,例如,

terminal : set a new user environment variable, not permanently终端:设置一个新的用户环境变量,不是永久的

export MY_TEST_PORT=9999

app.js : read the new environment variable from node app app.js : 从 node app 读取新的环境变量

console.log(process.env.MY_TEST_PORT)

terminal : run the node app and get the value终端:运行节点应用程序并获取值

$ node app.js
9999

Dotenv is a zero-dependency module that loads environment variables from a . Dotenv是一个零依赖模块,它从 . env file into process.env. env 文件process.env。 Storing configuration in the environment separate from code is based on The Twelve-Factor App methodology.在与代码分开的环境中存储配置基于十二因素应用程序方法。

with npm使用 npm

npm install dotenv npm 安装 dotenv

or with Yarn或用纱线

yarn add dotenv纱线添加 dotenv

Usage用法

As early as possible in your application, require and configure dotenv.尽早在您的应用程序中,要求并配置 dotenv。

require('dotenv').config()需要('dotenv').config()

first create a .env file in file explorer and write inside it:首先在文件资源管理器中创建一个 .env 文件并在其中写入:

PORT: 8080端口:8080

const http = require("http");

require("dotenv").config();

let port = process.env.PORT;
let host = process.env.HOST;

let server = http.createServer((req, res) => {
  console.log("Thanks for the request");
  res.writeHead(200, { "Content-Type": "text/plain" });
  res.end("You Rock");
});

server.listen(port, host, () => {
  console.log(`Server is listening ${host}:${port}`);
});

process.env.PORT || 3000 process.env.PORT || 3000 means: process.env.PORT means the PORT number you manually set. process.env.PORT || 3000表示: process.env.PORT表示您手动设置的PORT号。 3000 is the default port . 3000是默认port If you havent set it manually then it will listen to 3000.如果你没有手动设置它,那么它会听 3000。

app.set('port', process.env.PORT || 3000) or app.listen(3000) in your code means the same. app.set('port', process.env.PORT || 3000)app.listen(3000)意思相同。 It only says what port its supposed to listen as parameter from the environment.它只说明它应该从环境中监听哪个端口作为参数。

3000 is the hard-coded parameter which you pass to app.listen() , which means whenever you run your back-end code you're always going to listening on port 3000 , which might be for you or not, depending on your requirements and the requirements of the environment in which you're server is running. 3000是您传递给app.listen()的硬编码参数,这意味着每当您运行后端代码时,您总是会监听port 3000 ,这可能适合您,也可能不适合您,具体取决于您的要求以及您运行服务器的环境的要求。

Click to show 2 definitions.

(property) NodeJS.Process.env: NodeJS.ProcessEnv
The process.env property returns an object containing the user environment. See environ(7).

An example of this object looks like:

{
  TERM: 'xterm-256color',
  SHELL: '/usr/local/bin/bash',
  USER: 'maciej',
  PATH: '~/.bin/:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin',
  PWD: '/Users/maciej',
  EDITOR: 'vim',
  SHLVL: '1',
  HOME: '/Users/maciej',
  LOGNAME: 'maciej',
  _: '/usr/local/bin/node'
}
It is possible to modify this object, but such modifications will not be reflected outside the Node.js process, or (unless explicitly requested) to other Worker threads. In other words, the following example would not work:

$ node -e 'process.env.foo = "bar"' && echo $foo
While the following will:

import { env } from 'process';

env.foo = 'bar';
console.log(env.foo);
Assigning a property on process.env will implicitly convert the value to a string. This behavior is deprecated. Future versions of Node.js may throw an error when the value is not a string, number, or boolean.

import { env } from 'process';

env.test = null;
console.log(env.test);
// => 'null'
env.test = undefined;
console.log(env.test);
// => 'undefined'
Use delete to delete a property from process.env.

import { env } from 'process';

env.TEST = 1;
delete env.TEST;
console.log(env.TEST);
// => undefined
On Windows operating systems, environment variables are case-insensitive.

import { env } from 'process';

env.TEST = 1;
console.log(env.test);
// => 1
Unless explicitly specified when creating a Worker instance, each Worker thread has its own copy of process.env, based on its parent thread’s process.env, or whatever was specified as the env option to the Worker constructor. Changes to process.env will not be visible across Worker threads, and only the main thread can make changes that are visible to the operating system or to native add-ons.

@since — v0.1.27

What it is?这是什么?

The process.env global variable is injected by the Node at runtime for your application to use and it represents the state of the system environment your application is in when it starts. process.env 全局变量由 Node 在运行时注入供您的应用程序使用,它代表您的应用程序启动时所在系统环境的 state。 For example, if the system has a PATH variable set, this will be made accessible to you through process.env.PATH which you can use to check where binaries are located and make external calls to them if required.例如,如果系统设置了 PATH 变量,您可以通过 process.env.PATH 访问它,您可以使用它来检查二进制文件的位置,并在需要时对它们进行外部调用。

app.js应用程序.js

    const port = process.env.PORT || "3000";
    const server = require("./server");
    
    server.listen(port, () => {
      console.log(`Server listening at http://localhost:${port}`);
    });

server/index.js服务器/index.js

const express = require("express");
const routes = require("../routes");

const server = express();
server.use(express.json());

server.use("/api", routes);

module.exports = server;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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