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

NestJS使用npm ping报错:Cannot read properties of undefined (reading 'promise')

解决NestJS中使用npm ping包出现"Cannot read properties of undefined (reading 'promise')"错误的思路

问题场景

在NestJS项目中尝试使用npm ping包ping指定IP地址时,发送GET请求后收到500错误响应,NestJS日志报错如下:

[Nest] 17732 - 09/19/2022, 3:47:16 AM ERROR [ExceptionsHandler] Cannot read properties of undefined (reading 'promise')
TypeError: Cannot read properties of undefined (reading 'promise')

相关代码文件:

ping.controller.ts

import { Controller, Get } from '@nestjs/common';
import { PingService } from './ping.service';

@Controller('ping')
export class PingController {
  constructor(private pingService: PingService) {}
  @Get()
  pinger() {
    return this.pingService.ping();
  }
}

ping.service.ts

import { Injectable } from '@nestjs/common';
import ping from 'ping';
@Injectable()
export class PingService {
  async ping() {
    const result = await ping.promise.probe('192.168.43.73', {
      timeout: 10,
      extra: ['-i', '2'],
    });

    return console.log(result.alive);
  }
}

解决思路

1. 修正模块导入方式

npm ping包属于CommonJS模块,默认导出的结构需要通过命名空间导入才能正确访问promise属性。将ping.service.ts中的导入语句修改为:

import * as ping from 'ping';

2. 检查包版本兼容性

不同版本的ping包API存在差异,若上述修改后仍报错,查看package.json中的ping版本,对照官方文档确认调用方式。部分新版本可能直接提供异步方法,无需通过ping.promise层级调用。

3. 优化返回值逻辑

当前代码中return console.log(result.alive);会返回undefined,导致接口无有效数据返回。建议修改为返回实际检测结果:

return result.alive; // 或返回完整result对象:return result;

修正后的ping.service.ts示例

import { Injectable } from '@nestjs/common';
import * as ping from 'ping';

@Injectable()
export class PingService {
  async ping() {
    const result = await ping.promise.probe('192.168.43.73', {
      timeout: 10,
      extra: ['-i', '2'],
    });

    return result.alive;
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 21:05:22