1. 不报错,像是挂了空档
-正常的启动应该是下图这样的:
1.1 胡乱尝试
自以为是 node 或者 nest 框架的问题,进行了更换操作系统和包管理工具的场景(使用 yarn 运行之前要把 package-lock.json 删掉,否则安装过程中可能报错。)。
1. On Mac
Mac 的编译环境需要依赖于 xcode 工具。
$ xcode-select --install
xcode-select: error: command line tools are already installed,
use "Software Update" to install updates
# 提示已经安装的话,就重置
$ xcode-select --reset
npm install 和 yarn 都可以完成依赖包的安装
2. On Linux2
npm install 和 yarn 都可以完成依赖包的安装
3. On Ubuntu
npm install 和 yarn 都可以完成依赖包的安装
But!
-三种环境的启动结果都是一样的,如下图:
1.2 问题定位
nest new test-project
test-project 这个初始项目可以正常启动
用有问题的项目的 package.json 替换 test-project 项目中的 package.json,依然可以正常启动。
感觉不是 node 和 nest 的问题,可能是应用代码问题。
- 错误代码一
import {NestFactory} from '@nestjs/core';
import {AppModule} from './app.module';
import {CustomDbLogger} from './_basic/_logger/_logger.service';
import {PrismaService} from './_basic/_prisma/_prisma.service';
async function bootstrap() {
const app = await NestFactory.create(AppModule, {
bufferLogs: true,
});
//app.useLogger(new CustomDbLogger(await new PrismaService()));
app.useLogger(app.get(CustomDbLogger));
// Listen port
const port = process.env.PORT || 8080;
await app.listen(port);
}
bootstrap();
app.useLogger(app.get(CustomDbLogger));
CustomDBLogger的实例化需要一个参数,而这里的写法没有传参。
- 错误代码二
- log 方法中没有执行语句:
import {ConsoleLogger} from '@nestjs/common';
export class CustomLoggerService extends ConsoleLogger {
// stdout
debug(message: string) {
super.debug(message, this.context);
}
log(message: string) {
//super.log(message, this.context);
}
error(message: string) {
super.error(message, this.context);
}
warn(message: string) {
super.warn(message, this.context);
}
// stdout
verbose(message: string) {
super.verbose(message, this.context);
}
}
- log 方法中有super.log:
{
...
log(message: string) {
super.log(message, this.context);
}
...
}
- log 方法中有 super.error:
{
...
log(message: string) {
super.error(message, this.context);
}
...
}
问题的原因是,main.ts 中的 app.useLogger 需要使用 log 方法输出启动日志,如果 log 方法有问题就会导致启动时无任何信息输出的现象。
2. npm install --production 后执行 node main.js 报错
2.1 疑问
npm install --production 执行完已经生成了 dist 文件,难道这些 dist 文件的生成方式与 npm run build 的生成方式不同吗?
2.2 解决方法
执行 npm run build 后再执行 node main.js,就可以正常启动了。