npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

node-knife4j-ui

v1.1.4

Published

A Node.js wrapper for Knife4j UI to display Swagger/OpenAPI documentation

Readme

node-knife4j-ui

一个用于在Node.js应用中集成Knife4j UI界面的中间件,可以方便地展示Swagger/OpenAPI文档。对 CommonJS 和 ES Modules 的双重支持。

特性

  • 🚀 零依赖,轻量级中间件
  • 📚 支持Swagger/OpenAPI 3.0规范
  • 🎯 自动API分组显示
  • 🔧 灵活的配置选项
  • 📱 响应式UI设计

安装

npm install node-knife4j-ui

示例图片

引入方式

CommonJS

const { Knife4jDoc } = require('node-knife4j-ui');
const knife4jDoc = new Knife4jDoc(swaggerSpec);
// 或者
const Knife4jDoc = require('node-knife4j-ui').default;
const knife4jDoc = new Knife4jDoc(swaggerSpec);

ES Modules

import Knife4jDoc from 'node-knife4j-ui';
const knife4jDoc = new Knife4jDoc(swaggerSpec);
// 或者
import { Knife4jDoc } from 'node-knife4j-ui';
const knife4jDoc = new Knife4jDoc(swaggerSpec);

快速开始

注意事项

这个包使用中间件的方式写的接口,个人接口不能和这个包内部的中间件的判断冲突,否则不能正常使用

// 1.0.6之前
req.url.endsWith("/v3/api-docs/swagger-config")
req.url.endsWith("/swagger-resources")
req.url.startsWith("/api-docs/")
// 1.1.0之后
req.url === "/services.json"
req.url === `${prefix}/swagger.json`

重要:关于 services.json 接口

Knife4j UI 前端固定请求 /services.json 接口获取服务配置。当静态文件挂载在子路径(如 /doc)时,需要额外注册 serveRootServices 中间件来处理根路径请求。

为什么需要两个中间件?

请求 /doc/services.json  → serveExpress('/doc') 处理  → 返回服务配置
请求 /services.json      → serveRootServices('/doc') 处理 → 返回服务配置(Knife4j 前端 AJAX 请求)

| 请求路径 | 用途 | 处理中间件 | |---------|------|-----------| | /doc/services.json | 子路径请求 | serveExpress('/doc') | | /services.json | 根路径 AJAX 请求 | serveRootServices('/doc') | | /doc/swagger.json | Swagger JSON | serveExpress('/doc') |

express版本使用

个人测试node版本16

import express from 'express';
import swaggerJsdoc from 'swagger-jsdoc';
import swaggerUi from 'swagger-ui-express';
import Knife4jDoc from 'node-knife4j-ui';

const app = express();
const PORT = process.env.PORT || 3000;

// 中间件
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// Swagger配置选项
const swaggerOptions = {
  definition: {
    openapi: '3.0.0',
    info: {
      title: 'Express测试API',
      version: '1.0.0',
      description: '一个简单的Express API测试服务',
      contact: {
        name: 'API支持',
        email: '[email protected]'
      }
    },
    servers: [
      {
        url: `http://localhost:${PORT}`,
        description: '开发服务器'
      }
    ]
  },
  apis: ['./app.js'] // 指定包含JSDoc注释的文件
};

// 生成Swagger规范
const swaggerSpec = swaggerJsdoc(swaggerOptions);

// 提供Swagger UI
app.use('/swagger', swaggerUi.serve, swaggerUi.setup(swaggerSpec));
// 提供 Knife4j 文档
const knife4jDoc = new Knife4jDoc(swaggerSpec);
const knife4jDocPath = knife4jDoc.getKnife4jUiPath();
// 暴露静态文件服务
app.use('/doc', knife4jDoc.serveExpress('/doc'), express.static(knife4jDocPath));
// 处理根路径的 /services.json 请求(Knife4j 前端固定请求此路径)
app.use(knife4jDoc.serveRootServices('/doc'));

/**
 * @swagger
 * /test:
 *   get:
 *     summary: 测试接口
 *     description: 返回简单的问候信息
 *     tags:
 *       - 测试
 *     responses:
 *       200:
 *         description: 成功返回问候信息
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 message:
 *                   type: string
 *                   example: 你好!
 */
app.get('/test', (req, res) => {
  res.json({ message: '你好!' });
});

/**
 * @swagger
 * /getSwaggerSpec:
 *   get:
 *     summary: 获取Swagger规范
 *     description: 返回完整的Swagger规范对象
 *     tags:
 *       - Swagger
 *     responses:
 *       200:
 *         description: 成功返回Swagger规范
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 swaggerSpec:
 *                   type: object
 *                   description: Swagger规范对象
 */
app.get('/getSwaggerSpec', (req, res) => {
  res.json({ swaggerSpec });
});

// 启动服务器
app.listen(PORT, () => {
  console.log(`服务器运行在 http://localhost:${PORT}`);
  console.log(`Swagger文档地址: http://localhost:${PORT}/swagger`);
  console.log(`Knife4j文档地址: http://localhost:${PORT}/doc`);
});

export default app;

koa版本使用

个人测试node版本20,koa静态文件得使用18+才能正常使用

koa暴露静态文件不会自动拼接前缀,axios也没有自动拼接前缀写法有一点点不同

import Koa from 'koa';
import Router from 'koa-router';
import bodyParser from 'koa-bodyparser';
import cors from '@koa/cors';
import swaggerJsdoc from 'swagger-jsdoc';
import koaSwagger from 'koa2-swagger-ui';
import Knife4jDoc from 'node-knife4j-ui';
import serve from 'koa-static';
import mount from 'koa-mount';


const app = new Koa();
const router = new Router();
const PORT = process.env.PORT || 3001;

// 中间件
app.use(cors());
app.use(bodyParser());

// Swagger配置选项
const swaggerOptions = {
  definition: {
    openapi: '3.0.0',
    info: {
      title: 'Koa测试API',
      version: '1.0.0',
      description: '一个简单的Koa API测试服务',
      contact: {
        name: 'API支持',
        email: '[email protected]'
      }
    },
    servers: [
      {
        url: `http://localhost:${PORT}`,
        description: '开发服务器'
      }
    ]
  },
  apis: ['./koa-app.js'] // 指定包含JSDoc注释的文件
};

// 生成Swagger规范
const swaggerSpec = swaggerJsdoc(swaggerOptions);

// 提供Swagger UI
const swaggerUi = koaSwagger.koaSwagger({
  routePrefix: '/swagger',
  swaggerOptions: {
    spec: swaggerSpec
  },
});

// 提供 Knife4j 文档
const knife4jDoc = new Knife4jDoc(swaggerSpec);
const knife4jDocPath = knife4jDoc.getKnife4jUiPath();
// koa没有自动拼接前缀,不用转请求接口的前缀
app.use(knife4jDoc.serveKoa());
// 暴露静态文件服务,没有拼接前缀,需要将静态文件分开弄
app.use(mount('/doc', serve(knife4jDocPath, { index: 'index.html' })));
app.use(serve(knife4jDocPath));
// 处理根路径的 /services.json 请求(Knife4j 前端固定请求此路径)
app.use(knife4jDoc.serveKoaRootServices('/doc'));


/**
 * @swagger
 * /test:
 *   get:
 *     summary: 测试接口
 *     description: 返回简单的问候信息
 *     tags:
 *       - 测试
 *     responses:
 *       200:
 *         description: 成功返回问候信息
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 message:
 *                   type: string
 *                   example: 你好!
 */
router.get('/test', (ctx) => {
  ctx.body = { message: '你好!' };
});

/**
 * @swagger
 * /getSwaggerSpec:
 *   get:
 *     summary: 获取Swagger规范
 *     description: 返回完整的Swagger规范对象
 *     tags:
 *       - Swagger
 *     responses:
 *       200:
 *         description: 成功返回Swagger规范
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 swaggerSpec:
 *                   type: object
 *                   description: Swagger规范对象
 */
router.get('/getSwaggerSpec', (ctx) => {
  ctx.body = { swaggerSpec };
});

// 应用路由
app.use(router.routes());
app.use(router.allowedMethods());

// 应用Swagger UI
app.use(swaggerUi);

// 启动服务器
app.listen(PORT, () => {
  console.log(`Koa服务器运行在 http://localhost:${PORT}`);
  console.log(`Swagger文档地址: http://localhost:${PORT}/swagger`);
  console.log(`Knife4j文档地址: http://localhost:${PORT}/doc`);
});

export default app;

nestjs使用

得按照自己使用的底层框架使用,下面是express作为底层框架的核心代码

import { SwaggerModule } from "@nestjs/swagger";
import Knife4jDoc from "node-knife4j-ui";
import * as express from "express";

// 创建 Swagger 文档
const document = SwaggerModule.createDocument(app, SwaggerConfig.swaggerOptions);
const knife4jDoc = new Knife4jDoc(document);
const knife4jDocPath = knife4jDoc.getKnife4jUiPath();
// 暴露静态文件服务
app.use("/test", knife4jDoc.serveExpress("/test"), express.static(knife4jDocPath));
// 处理根路径的 /services.json 请求(Knife4j 前端固定请求此路径)
app.use(knife4jDoc.serveRootServices("/test"));