You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

macOS 15.0.1下Fastify使用server.listen时tsup watch失效问题

问题:Fastify应用在macOS 15.0.1下使用tsup watch模式无法自动重启

在macOS 15.0.1系统开发Fastify应用时,只要代码中包含server.listen,应用就无法自动重建和重启。使用tsup的watch模式监听文件变更并重建,但添加server.listen后,watch模式会停止检测文件变化。

相关配置代码

入口文件(index.ts)

import buildServer from './server';

async function main(): Promise<void> {
  const server = await buildServer();

  server.listen({ port: 4000, host: '0.0.0.0' });
}

void main();

server.ts

import type { FastifyInstance } from 'fastify';
import fastifyHelmet from '@fastify/helmet';
import Fastify from 'fastify';
import { serverOptions } from './configs';

const server = Fastify(serverOptions);

async function buildServer(): Promise<FastifyInstance> {
  server.register(fastifyHelmet);
  return server;
}

export default buildServer;

tsup配置(tsup.config.js)

import { defineConfig } from 'tsup';

export default defineConfig(options => ({
  entry: ['src/**/*.ts'],
  clean: true,
  format: ['cjs'],
  ...options,
}));

执行命令

tsup --watch --onSuccess 'node dist/index.js'

解决方法

1. 用nodemon管理进程重启

tsup的--onSuccess启动的node进程会长期运行,导致后续文件变更无法触发重启。改用nodemon监控dist目录,自动重启应用:

首先安装nodemon:

npm install -D nodemon

修改执行命令:

tsup --watch --onSuccess 'nodemon --watch dist --delay 100ms dist/index.js'

2. 让应用正确响应终止信号

添加信号监听,确保进程能被正常终止,避免端口占用和进程残留:

更新入口文件:

import buildServer from './server';

async function main(): Promise<void> {
  const server = await buildServer();

  const address = await server.listen({ port: 4000, host: '0.0.0.0' });
  console.log(`Server running at ${address}`);

  // 监听终止信号,优雅关闭服务器
  process.on('SIGTERM', async () => {
    console.log('收到SIGTERM信号,正在关闭服务器...');
    await server.close();
    process.exit(0);
  });

  process.on('SIGINT', async () => {
    console.log('收到SIGINT信号,正在关闭服务器...');
    await server.close();
    process.exit(0);
  });
}

void main();

3. 优化tsup配置(可选)

仅编译入口文件,减少不必要的编译和监听:

修改tsup.config.js:

import { defineConfig } from 'tsup';

export default defineConfig(options => ({
  entry: ['src/index.ts'],
  clean: true,
  format: ['cjs'],
  ...options,
}));

内容的提问来源于stack exchange,提问作者Nazar Duma

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 21:12:38