Skip to content

Application(应用程序)

Application 类负责连接 AdonisJS 应用程序的所有繁重工作。你可以使用此类来了解应用程序运行的环境、获取应用程序的当前状态或创建指向特定目录的路径。

另请参阅:应用程序生命周期

环境

环境指的是应用程序的运行时环境。应用程序始终在以下已知环境之一中启动。

  • web 环境指的是为 HTTP 服务器启动的进程。

  • console 环境指的是除 REPL 命令之外的 Ace 命令。

  • repl 环境指的是使用 node ace repl 命令启动的进程。

  • 最后,test 环境指的是使用 node ace test 命令启动的进程。

你可以使用 getEnvironment 方法访问应用程序环境。

ts
import app from '@adonisjs/core/services/app'

console.log(app.getEnvironment())

你也可以在应用程序启动之前切换应用程序环境。REPL 命令就是一个很好的例子。

node ace repl 命令在 console 环境中启动应用程序,但该命令在内部在呈现 REPL 提示符之前将环境切换到 repl

ts
if (!app.isBooted) {
	app.setEnvironment('repl')
}

Node 环境

你可以使用 nodeEnvironment 属性访问 Node.js 环境。该值是对 NODE_ENV 环境变量的引用。但是,该值会进一步规范化以保持一致。

ts
import app from '@adonisjs/core/services/app'

console.log(app.nodeEnvironment)
NODE_ENV规范化为
devdevelopment
developdevelopment
stagestaging
prodproduction
testingtest

此外,你可以使用以下属性作为简写来了解当前环境。

  • inProduction:检查应用程序是否在生产环境中运行。
  • inDev:检查应用程序是否在开发环境中运行。
  • inTest:检查应用程序是否在测试环境中运行。
ts
import app from '@adonisjs/core/services/app'

// 是否在生产环境
app.inProduction
app.nodeEnvironment === 'production'

// 是否在开发环境
app.inDev
app.nodeEnvironment === 'development'

// 是否在测试环境
app.inTest
app.nodeEnvironment === 'test'

状态

状态指的是应用程序的当前状态。你可以访问的框架功能在很大程度上取决于应用程序的当前状态。例如,在应用程序处于 booted 状态之前,你无法访问容器绑定容器服务

应用程序始终处于以下已知状态之一。

  • created:这是应用程序的默认状态。

  • initiated:在此状态下,我们解析/验证环境变量并处理 adonisrc.ts 文件。

  • booted:在此状态下,应用程序服务提供者已注册并启动。

  • ready:ready 状态因环境而异。例如,在 web 环境中,ready 状态意味着应用程序已准备好接受新的 HTTP 请求。

  • terminated:应用程序已终止,进程将很快退出。在 web 环境中,应用程序将不接受新的 HTTP 请求。

ts
import app from '@adonisjs/core/services/app'

console.log(app.getState())

你也可以使用以下简写属性来了解应用程序是否处于给定状态。

ts
import app from '@adonisjs/core/services/app'

// 应用程序已启动
app.isBooted
app.getState() !== 'created' && app.getState() !== 'initiated'

// 应用程序已就绪
app.isReady
app.getState() === 'ready'

// 正在优雅地尝试终止应用程序
app.isTerminating

// 应用程序已终止
app.isTerminated
app.getState() === 'terminated'

监听进程信号

你可以使用 app.listenapp.listenOnce 方法监听 POSIX 信号。在底层,我们使用 Node.js process 对象注册监听器。

ts
import app from '@adonisjs/core/services/app'

// 监听 SIGTERM 信号
app.listen('SIGTERM', () => {
})

// 只监听一次 SIGTERM 信号
app.listenOnce('SIGTERM', () => {
})

有时,你可能想有条件地注册监听器。例如,在 pm2 环境中运行时监听 SIGINT 信号。

你可以使用 listenIflistenOnceIf 方法有条件地注册监听器。只有当第一个参数的值为真值时才会注册监听器。

ts
import app from '@adonisjs/core/services/app'

app.listenIf(app.managedByPm2, 'SIGTERM', () => {
})

app.listenOnceIf(app.managedByPm2, 'SIGTERM', () => {
})

通知父进程

如果你的应用程序作为子进程启动,你可以使用 app.notify 方法向父进程发送消息。在底层,我们使用 process.send 方法。

ts
import app from '@adonisjs/core/services/app'

app.notify('ready')

app.notify({
  isReady: true,
  port: 3333,
  host: 'localhost'
})

创建项目文件的 URL 和路径

我们强烈建议使用以下辅助方法,而不是自己构建绝对 URL 或项目文件的路径。

makeURL

makeURL 方法返回项目根目录中给定文件或目录的文件 URL。例如,你可以在导入文件时生成 URL。

ts
import app from '@adonisjs/core/services/app'

const files = [
  './tests/welcome.spec.ts',
  './tests/maths.spec.ts'
]

await Promise.all(files.map((file) => {
  return import(app.makeURL(file).href)
}))

makePath

makePath 方法返回项目根目录中给定文件或目录的绝对路径。

ts
import app from '@adonisjs/core/services/app'

app.makePath('app/middleware/auth.ts')

configPath

返回项目 config 目录中文件的路径。

ts
app.configPath('shield.ts')
// /project_root/config/shield.ts

app.configPath()
// /project_root/config

publicPath

返回项目 public 目录中文件的路径。

ts
app.publicPath('style.css')
// /project_root/public/style.css

app.publicPath()
// /project_root/public

providersPath

返回 providers 目录中文件的路径。

ts
app.providersPath('app_provider')
// /project_root/providers/app_provider.ts

app.providersPath()
// /project_root/providers

factoriesPath

返回数据库 factories 目录中文件的路径。

ts
app.factoriesPath('user.ts')
// /project_root/database/factories/user.ts

app.factoriesPath()
// /project_root/database/factories

migrationsPath

返回数据库 migrations 目录中文件的路径。

ts
app.migrationsPath('user.ts')
// /project_root/database/migrations/user.ts

app.migrationsPath()
// /project_root/database/migrations

seedersPath

返回数据库 seeders 目录中文件的路径。

ts
app.seedersPath('user.ts')
// /project_root/database/seeders/users.ts

app.seedersPath()
// /project_root/database/seeders

languageFilesPath

返回语言文件目录中文件的路径。

ts
app.languageFilesPath('en/messages.json')
// /project_root/resources/lang/en/messages.json

app.languageFilesPath()
// /project_root/resources/lang

viewsPath

返回 views 目录中文件的路径。

ts
app.viewsPath('welcome.edge')
// /project_root/resources/views/welcome.edge

app.viewsPath()
// /project_root/resources/views

startPath

返回 start 目录中文件的路径。

ts
app.startPath('routes.ts')
// /project_root/start/routes.ts

app.startPath()
// /project_root/start

tmpPath

返回项目根目录中 tmp 目录内文件的路径。

ts
app.tmpPath('logs/mail.txt')
// /project_root/tmp/logs/mail.txt

app.tmpPath()
// /project_root/tmp

httpControllersPath

返回 HTTP controllers 目录中文件的路径。

ts
app.httpControllersPath('users_controller.ts')
// /project_root/app/controllers/users_controller.ts

app.httpControllersPath()
// /project_root/app/controllers

modelsPath

返回 models 目录中文件的路径。

ts
app.modelsPath('user.ts')
// /project_root/app/models/user.ts

app.modelsPath()
// /project_root/app/models

servicesPath

返回 services 目录中文件的路径。

ts
app.servicesPath('user.ts')
// /project_root/app/services/user.ts

app.servicesPath()
// /project_root/app/services

exceptionsPath

返回 exceptions 目录中文件的路径。

ts
app.exceptionsPath('handler.ts')
// /project_root/app/exceptions/handler.ts

app.exceptionsPath()
// /project_root/app/exceptions

mailsPath

返回 mails 目录中文件的路径。

ts
app.mailsPath('verify_email.ts')
// /project_root/app/mails/verify_email.ts

app.mailsPath()
// /project_root/app/mails

middlewarePath

返回 middleware 目录中文件的路径。

ts
app.middlewarePath('auth.ts')
// /project_root/app/middleware/auth.ts

app.middlewarePath()
// /project_root/app/middleware

policiesPath

返回 policies 目录中文件的路径。

ts
app.policiesPath('posts.ts')
// /project_root/app/polices/posts.ts

app.policiesPath()
// /project_root/app/polices

validatorsPath

返回 validators 目录中文件的路径。

ts
app.validatorsPath('create_user.ts')
// /project_root/app/validators/create_user.ts

app.validatorsPath()
// /project_root/app/validators/create_user.ts

commandsPath

返回 commands 目录中文件的路径。

ts
app.commandsPath('greet.ts')
// /project_root/commands/greet.ts

app.commandsPath()
// /project_root/commands

eventsPath

返回 events 目录中文件的路径。

ts
app.eventsPath('user_created.ts')
// /project_root/app/events/user_created.ts

app.eventsPath()
// /project_root/app/events

listenersPath

返回 listeners 目录中文件的路径。

ts
app.listenersPath('send_invoice.ts')
// /project_root/app/listeners/send_invoice.ts

app.listenersPath()
// /project_root/app/listeners

生成器

生成器用于为不同的实体创建类名和文件名。例如,你可以使用 generators.controllerFileName 方法生成控制器的文件名。

ts
import app from '@adonisjs/core/services/app'

app.generators.controllerFileName('user')
// 输出 - users_controller.ts

app.generators.controllerName('user')
// 输出 - UsersController

参考 generators.ts 源代码查看可用生成器列表。


Application (English Version)

The Application class does all the heavy lifting of wiring together an AdonisJS application. You can use this class to know about the environment in which your app is running, get the current state of the application, or make paths to specific directories.

See also: Application lifecycle

Environment

The environment refers to the application runtime environment. The application is always booted in one of the following known environments.

  • web environment refers to the process started for the HTTP server.

  • console environment refers to the Ace commands except for the REPL command.

  • repl environment refers to the process started using the node ace repl command.

  • Finally, the test environment refers to the process started using the node ace test command.

You can access the application environment using the getEnvironment method.

ts
import app from '@adonisjs/core/services/app'

console.log(app.getEnvironment())

You can also switch the application environment before it has been booted. A great example of this is the REPL command.

The node ace repl command starts the application in the console environment, but the command internally switches the environment to repl before presenting the REPL prompt.

ts
if (!app.isBooted) {
	app.setEnvironment('repl')
}

Node environment

You can access the Node.js environment using the nodeEnvironment property. The value is a reference to the NODE_ENV environment variable. However, the value is further normalized to be consistent.

ts
import app from '@adonisjs/core/services/app'

console.log(app.nodeEnvironment)
NODE_ENVNormalized to
devdevelopment
developdevelopment
stagestaging
prodproduction
testingtest

Also, you can use the following properties as a shorthand to know the current environment.

  • inProduction: Check if the application is running in the production environment.
  • inDev: Check if the application is running in the development environment.
  • inTest: Check if the application is running in the test environment.
ts
import app from '@adonisjs/core/services/app'

// Is in production
app.inProduction
app.nodeEnvironment === 'production'

// Is in development
app.inDev
app.nodeEnvironment === 'development'

// Is in the test
app.inTest
app.nodeEnvironment === 'test'

State

The state refers to the current state of the application. The framework features you can access significantly depend upon the current state of the application. For example, you cannot access the container bindings or container services until the app is in a booted state.

The application is always in one of the following known states.

  • created: It is the default state of the application.

  • initiated: In this state, we parse/validate the environment variables and process the adonisrc.ts file.

  • booted: The application service providers are registered and booted at this state.

  • ready: The ready state varies between different environments. For example, in the web environment, the ready state means the application is ready to accept new HTTP requests.

  • terminated: The application has been terminated, and the process will exit shortly. The application will not accept new HTTP requests in the web environment.

ts
import app from '@adonisjs/core/services/app'

console.log(app.getState())

You can also use the following shorthand properties to know whether the application is in a given state.

ts
import app from '@adonisjs/core/services/app'

// App is booted
app.isBooted
app.getState() !== 'created' && app.getState() !== 'initiated'

// App is ready
app.isReady
app.getState() === 'ready'

// gracefully attempting to terminate the app
app.isTerminating

// App has been terminated
app.isTerminated
app.getState() === 'terminated'

Listening for process signals

You can listen for POSIX signals using the app.listen, or app.listenOnce methods. Under the hood, we register the listener with the Node.js process object.

ts
import app from '@adonisjs/core/services/app'

// Listen for a SIGTERM signal
app.listen('SIGTERM', () => {
})

// Listen once for a SIGTERM signal
app.listenOnce('SIGTERM', () => {
})

At times, you might want to register the listeners conditionally. For example, listen to the SIGINT signal when running inside the pm2 environment.

You can use the listenIf or listenOnceIf methods to register a listener conditionally. The listener is only registered when the first argument's value is truthy.

ts
import app from '@adonisjs/core/services/app'

app.listenIf(app.managedByPm2, 'SIGTERM', () => {
})

app.listenOnceIf(app.managedByPm2, 'SIGTERM', () => {
})

Notifying parent process

If your application starts as a child process, you can send messages to the parent process using the app.notify method. Under the hood, we use the process.send method.

ts
import app from '@adonisjs/core/services/app'

app.notify('ready')

app.notify({
  isReady: true,
  port: 3333,
  host: 'localhost'
})

Making URLs and paths to project files

Instead of self-constructing absolute URLs or paths to project files, we highly recommend using the following helpers.

makeURL

The make URL method returns a file URL to a given file or directory within the project root. For example, you may generate a URL when importing a file.

ts
import app from '@adonisjs/core/services/app'

const files = [
  './tests/welcome.spec.ts',
  './tests/maths.spec.ts'
]

await Promise.all(files.map((file) => {
  return import(app.makeURL(file).href)
}))

makePath

The makePath method returns an absolute path to a given file or directory within the project root.

ts
import app from '@adonisjs/core/services/app'

app.makePath('app/middleware/auth.ts')

configPath

Returns path to a file inside the project's config directory.

ts
app.configPath('shield.ts')
// /project_root/config/shield.ts

app.configPath()
// /project_root/config

publicPath

Returns path to a file inside the project's public directory.

ts
app.publicPath('style.css')
// /project_root/public/style.css

app.publicPath()
// /project_root/public

providersPath

Returns path to a file inside the provider's directory.

ts
app.providersPath('app_provider')
// /project_root/providers/app_provider.ts

app.providersPath()
// /project_root/providers

factoriesPath

Returns path to a file inside the database factories directory.

ts
app.factoriesPath('user.ts')
// /project_root/database/factories/user.ts

app.factoriesPath()
// /project_root/database/factories

migrationsPath

Returns path to a file inside the database migrations directory.

ts
app.migrationsPath('user.ts')
// /project_root/database/migrations/user.ts

app.migrationsPath()
// /project_root/database/migrations

seedersPath

Returns path to a file inside the database seeders directory.

ts
app.seedersPath('user.ts')
// /project_root/database/seeders/users.ts

app.seedersPath()
// /project_root/database/seeders

languageFilesPath

Returns path to a file inside languages directory.

ts
app.languageFilesPath('en/messages.json')
// /project_root/resources/lang/en/messages.json

app.languageFilesPath()
// /project_root/resources/lang

viewsPath

Returns path to a file inside the views directory.

ts
app.viewsPath('welcome.edge')
// /project_root/resources/views/welcome.edge

app.viewsPath()
// /project_root/resources/views

startPath

Returns path to a file inside the start directory.

ts
app.startPath('routes.ts')
// /project_root/start/routes.ts

app.startPath()
// /project_root/start

tmpPath

Returns path to a file inside the tmp directory within the project root.

ts
app.tmpPath('logs/mail.txt')
// /project_root/tmp/logs/mail.txt

app.tmpPath()
// /project_root/tmp

httpControllersPath

Returns path to a file inside the HTTP controllers directory.

ts
app.httpControllersPath('users_controller.ts')
// /project_root/app/controllers/users_controller.ts

app.httpControllersPath()
// /project_root/app/controllers

modelsPath

Returns path to a file inside the model's directory.

ts
app.modelsPath('user.ts')
// /project_root/app/models/user.ts

app.modelsPath()
// /project_root/app/models

servicesPath

Returns path to a file inside the services directory.

ts
app.servicesPath('user.ts')
// /project_root/app/services/user.ts

app.servicesPath()
// /project_root/app/services

exceptionsPath

Returns path to a file inside the exceptions directory.

ts
app.exceptionsPath('handler.ts')
// /project_root/app/exceptions/handler.ts

app.exceptionsPath()
// /project_root/app/exceptions

mailsPath

Returns path to a file inside the mails directory.

ts
app.mailsPath('verify_email.ts')
// /project_root/app/mails/verify_email.ts

app.mailsPath()
// /project_root/app/mails

middlewarePath

Returns path to a file inside the middleware directory.

ts
app.middlewarePath('auth.ts')
// /project_root/app/middleware/auth.ts

app.middlewarePath()
// /project_root/app/middleware

policiesPath

Returns path to a file inside the policies directory.

ts
app.policiesPath('posts.ts')
// /project_root/app/polices/posts.ts

app.policiesPath()
// /project_root/app/polices

validatorsPath

Returns path to a file inside the validators directory.

ts
app.validatorsPath('create_user.ts')
// /project_root/app/validators/create_user.ts

app.validatorsPath()
// /project_root/app/validators/create_user.ts

commandsPath

Returns path to a file inside the commands directory.

ts
app.commandsPath('greet.ts')
// /project_root/commands/greet.ts

app.commandsPath()
// /project_root/commands

eventsPath

Return path to a file inside the events directory.

ts
app.eventsPath('user_created.ts')
// /project_root/app/events/user_created.ts

app.eventsPath()
// /project_root/app/events

listenersPath

Return path to a file inside the listeners directory.

ts
app.listenersPath('send_invoice.ts')
// /project_root/app/listeners/send_invoice.ts

app.listenersPath()
// /project_root/app/listeners

Generators

Generators are used to create class names and file names for different entities. For example, you may use the generators.controllerFileName method to generate the filename for a controller.

ts
import app from '@adonisjs/core/services/app'

app.generators.controllerFileName('user')
// output - users_controller.ts

app.generators.controllerName('user')
// output - UsersController

Please reference the generators.ts source code to view the list of available generators.