# egg-core

> A core Pluggable framework based on koa

Latest version **5.5.1** (published 2025-01-22) · MIT license · 0 weekly downloads

## Install

```sh
npm install egg-core
pnpm add egg-core
yarn add egg-core
bun add egg-core
```

## Health

**Score 50/100 (C)** — status: stable.

Positive: has types; no vulnerabilities; has provenance; high quality score.

Warnings: low downloads; no esm support.

Negative: stale.

## Facts

| | |
|---|---|
| Version | 5.5.1 |
| Published | 2025-01-22 |
| First published | 2016-05-26 |
| Weekly downloads | 0 |
| License | MIT |
| TypeScript types | bundled |
| Module format | CommonJS |
| Node | >= 14.19.0 |
| Dependencies | 19 |
| Unpacked size | 107.7 KB |
| Known vulnerabilities | 0 |
| Install scripts | no |
| Provenance | attested (GitHub Actions) |
| GitHub stars | 219 |
| Author | gxcsoccer |
| Maintainers | gxkl, eggjs-admin, fengmk2, atian25, dead_horse, wanghx, hyj1991, killagu, coolme200, mansonchor.zzw, hubcarl, gemwuu, akitasummer, gxcsoccer, popomore |
| Keywords | egg, loader |

## Links

- npm: https://www.npmjs.com/package/egg-core
- Repository: https://github.com/eggjs/core
- Homepage: https://github.com/eggjs/core#readme
- Issues: https://github.com/eggjs/egg/issues
- npm.io page: https://npm.io/package/egg-core

## Dependencies (19)

- [co](https://npm.io/package/co.md) ^4.6.0
- [koa](https://npm.io/package/koa.md) ^2.14.0
- [depd](https://npm.io/package/depd.md) ^2.0.0
- [gals](https://npm.io/package/gals.md) ^1.0.1
- [debug](https://npm.io/package/debug.md) ^4.1.1
- [globby](https://npm.io/package/globby.md) ^11.0.2
- [extend2](https://npm.io/package/extend2.md) ^1.0.0
- [utility](https://npm.io/package/utility.md) ^1.16.1
- [get-ready](https://npm.io/package/get-ready.md) ^2.0.1
- [@types/koa](https://npm.io/package/@types/koa.md) ^2.13.5
- [egg-logger](https://npm.io/package/egg-logger.md) ^3.1.0
- [is-type-of](https://npm.io/package/is-type-of.md) ^1.2.1
- [@types/depd](https://npm.io/package/@types/depd.md) ^1.1.32
- [koa-convert](https://npm.io/package/koa-convert.md) ^1.2.0
- [node-homedir](https://npm.io/package/node-homedir.md) ^1.1.1
- [@eggjs/router](https://npm.io/package/@eggjs/router.md) ^2.2.0
- [ready-callback](https://npm.io/package/ready-callback.md) ^3.0.0
- [tsconfig-paths](https://npm.io/package/tsconfig-paths.md) ^4.1.1
- [egg-path-matching](https://npm.io/package/egg-path-matching.md) ^1.2.0

## Recent versions

- 5.5.1 (latest) — 2025-01-22
- 4.31.0 (latest-4) — 2023-12-31
- 3.21.4 (latest-3) — 2019-05-14
- 5.5.0 — 2025-01-22
- 5.4.1 — 2023-12-19
- 5.4.0 — 2023-12-19
- 4.30.2 — 2023-04-07
- 5.3.1 — 2023-04-06
- 5.3.0 — 2023-01-13
- 5.2.0 — 2023-01-03
- 5.1.1 — 2023-01-01
- 5.1.0 — 2023-01-01
- 5.0.0 — 2023-01-01
- 4.30.1 — 2022-12-19
- 4.30.0 — 2022-12-19
- … 124 more at https://npm.io/package/egg-core/versions

## README

# egg-core

[![NPM version][npm-image]][npm-url]
[![Node.js CI](https://github.com/eggjs/egg-core/actions/workflows/nodejs-5.x.yml/badge.svg)](https://github.com/eggjs/egg-core/actions/workflows/nodejs-5.x.yml)
[![Test coverage][codecov-image]][codecov-url]
[![Known Vulnerabilities][snyk-image]][snyk-url]
[![npm download][download-image]][download-url]

[npm-image]: https://img.shields.io/npm/v/egg-core.svg?style=flat-square
[npm-url]: https://npmjs.org/package/egg-core
[codecov-image]: https://codecov.io/github/eggjs/egg-core/coverage.svg?branch=master
[codecov-url]: https://codecov.io/github/eggjs/egg-core?branch=master
[snyk-image]: https://snyk.io/test/npm/egg-core/badge.svg?style=flat-square
[snyk-url]: https://snyk.io/test/npm/egg-core
[download-image]: https://img.shields.io/npm/dm/egg-core.svg?style=flat-square
[download-url]: https://npmjs.org/package/egg-core

A core Pluggable framework based on [koa](https://github.com/koajs/koa).

**Don't use it directly, see [egg](https://github.com/eggjs/egg).**

## Usage

Directory structure

```
├── package.json
├── app.js (optional)
├── agent.js (optional)
├── app
|   ├── router.js
│   ├── controller
│   │   └── home.js
|   ├── extend (optional)
│   |   ├── helper.js (optional)
│   |   ├── filter.js (optional)
│   |   ├── request.js (optional)
│   |   ├── response.js (optional)
│   |   ├── context.js (optional)
│   |   ├── application.js (optional)
│   |   └── agent.js (optional)
│   ├── service (optional)
│   ├── middleware (optional)
│   │   └── response_time.js
│   └── view (optional)
|       ├── layout.html
│       └── home.html
├── config
|   ├── config.default.js
│   ├── config.prod.js
|   ├── config.test.js (optional)
|   ├── config.local.js (optional)
|   ├── config.unittest.js (optional)
│   └── plugin.js
```

Then you can start with code below

```js
const Application = require('egg-core').EggCore;
const app = new Application({
  baseDir: '/path/to/app'
});
app.ready(() => app.listen(3000));
```

## EggLoader

EggLoader can easily load files or directories in your [egg] project. In addition, you can customize the loader with low level APIs.

### constructor

- {String} baseDir - current directory of application
- {Object} app - instance of egg application
- {Object} plugins - merge plugins for test
- {Logger} logger - logger instance，default is console

### High Level APIs

#### loadPlugin

Load config/plugin.js

#### loadConfig

Load config/config.js and config/{serverEnv}.js

If `process.env.EGG_APP_CONFIG` is exists, then it will be parse and override config.

#### loadController

Load app/controller

#### loadMiddleware

Load app/middleware

#### loadApplicationExtend

Load app/extend/application.js

#### loadContextExtend

Load app/extend/context.js

#### loadRequestExtend

Load app/extend/request.js

#### loadResponseExtend

Load app/extend/response.js

#### loadHelperExtend

Load app/extend/helper.js

#### loadCustomApp

Load app.js, if app.js export boot class, then trigger configDidLoad

#### loadCustomAgent

Load agent.js, if agent.js export boot class, then trigger configDidLoad

#### loadService

Load app/service

### Low Level APIs

#### getServerEnv()

Retrieve application environment variable values via `serverEnv`. You can access directly by calling `this.serverEnv` after instantiation.

serverEnv | description
---       | ---
default   | default environment
test      | system integration testing environment
prod      | production environment
local     | local environment on your own computer
unittest  | unit test environment

#### getEggPaths()

To get directories of the frameworks. A new framework is created by extending egg, then you can use this function to get all frameworks.

#### getLoadUnits()

A loadUnit is a directory that can be loaded by EggLoader, cause it has the same structure.

This function will get add loadUnits follow the order:

1. plugin
2. framework
3. app

loadUnit has a path and a type. Type must be one of those values: *app*, *framework*, *plugin*.

```js
{
  path: 'path/to/application',
  type: 'app'
}
```

#### getAppname()

To get application name from *package.json*

#### appInfo

Get the infomation of the application

- pkg: `package.json`
- name: the application name from `package.json`
- baseDir: current directory of application
- env: equals to serverEnv
- HOME: home directory of the OS
- root: baseDir when local and unittest, HOME when other environment

#### loadFile(filepath)

To load a single file. **Note:** The file must export as a function.

#### loadToApp(directory, property, LoaderOptions)

To load files from directory in the application.

Invoke `this.loadToApp('$baseDir/app/controller', 'controller')`, then you can use it by `app.controller`.

#### loadToContext(directory, property, LoaderOptions)

To load files from directory, and it will be bound the context.

```js
// define service in app/service/query.js
module.exports = class Query {
  constructor(ctx) {
    super(ctx);
    // get the ctx
  }

  async get() {}
};

// use the service in app/controller/home.js
module.exports = async ctx => {
  ctx.body = await ctx.service.query.get();
};
```

#### loadExtend(name, target)

Loader app/extend/xx.js to target, For example,

```js
this.loadExtend('application', app);
```

### LoaderOptions

Param          | Type           | Description
-------------- | -------------- | ------------------------
directory      | `String/Array` | directories to be loaded
target         | `Object`       | attach the target object from loaded files
match          | `String/Array` | match the files when load, default to `**/*.js`(if process.env.EGG_TYPESCRIPT was true, default to `[ '**/*.(js|ts)', '!**/*.d.ts' ]`)
ignore         | `String/Array` | ignore the files when load
initializer    | `Function`     | custom file exports, receive two parameters, first is the inject object(if not js file, will be content buffer), second is an `options` object that contain `path`
caseStyle      | `String/Function` | set property's case when converting a filepath to property list.
override       | `Boolean`      | determine whether override the property when get the same name
call           | `Boolean`      | determine whether invoke when exports is function
inject         | `Object`       | an object that be the argument when invoke the function
filter         | `Function`     | a function that filter the exports which can be loaded

## Timing

EggCore record boot progress with `Timing`, include:

- Process start time
- Script start time(node don't implement an interface like `process.uptime` to record the script start running time, framework can implement a prestart file used with node `--require` options to set `process.scriptTime`)
- Application start time
- Load duration
- `require` duration

### start

Start record a item. If the item exits, end the old one and start a new one.

- {String} name - record item name
- {Number} [start] - record item start time, default is Date.now()

### end

End a item.

- {String} name - end item name

### toJSON

Generate all record items to json

- {String} name - record item name
- {Number} start - item start time
- {Number} end - item end time
- {Number} duration - item duration
- {Number} pid - pid
- {Number} index - item index

## Questions & Suggestions

Please open an issue [here](https://github.com/eggjs/egg/issues).

## License

[MIT](LICENSE)

## Contributors

[![Contributors](https://contrib.rocks/image?repo=eggjs/core)](https://github.com/eggjs/core/graphs/contributors)

Made with [contributors-img](https://contrib.rocks).

---
_Source: https://npm.io/package/egg-core · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
