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

TypeScript文件无法读取同目录.pem文件,求解决方案

解决TypeScript读取同目录.pem文件的ENOENT错误及导入问题

问题根源

./cert.pem是相对于Node.js执行时的工作目录,而非你的TypeScript文件所在目录,这是导致找不到文件的核心原因。另外TypeScript默认不识别.pem这类非代码文件的导入规则,所以会出现导入提示不显示的问题。

解决方案

1. 使用绝对路径读取文件(最直接的解决方法)

通过获取当前TypeScript文件的绝对目录,再拼接.pem文件路径,彻底避免工作目录差异带来的问题:

若使用CommonJS模块(tsconfig.json中module为CommonJS)

import * as fs from 'fs';
import * as path from 'path';

const certPath = path.join(__dirname, './cert.pem');
const keyPath = path.join(__dirname, './key.pem');

const dataServiceTlsSecret = addResource(
    new Secret({
      metadata: {
        name: DATA_SERVICE,
      },
      type: "kubernetes.io/tls",
      stringData: {
        "tls.crt": fs.readFileSync(certPath, 'utf-8'),
        "tls.key": fs.readFileSync(keyPath, 'utf-8'),
      }
    })
);

若使用ES模块(tsconfig.json中module为ESNext/ES2020等)

import * as fs from 'fs';
import * as path from 'path';
import { fileURLToPath } from 'url';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

const certPath = path.join(__dirname, './cert.pem');
const keyPath = path.join(__dirname, './key.pem');

const dataServiceTlsSecret = addResource(
    new Secret({
      metadata: {
        name: DATA_SERVICE,
      },
      type: "kubernetes.io/tls",
      stringData: {
        "tls.crt": fs.readFileSync(certPath, 'utf-8'),
        "tls.key": fs.readFileSync(keyPath, 'utf-8'),
      }
    })
);

2. 确保编译后.pem文件存在于输出目录

如果使用tsc编译TypeScript,默认不会复制.pem这类非.ts文件到输出目录(比如dist),需要额外配置:

  • 在tsconfig.json中添加include规则:
{
  "include": [
    "src/**/*",
    "src/**/*.pem" // 包含所有.pem文件
  ]
}
  • 或者使用工具(如copyfiles)在编译后复制文件:
    先安装依赖:npm install copyfiles --save-dev
    然后在package.json的scripts中添加:
    "scripts": {
      "build": "tsc && copyfiles src/*.pem dist/"
    }
    

3. 让TypeScript支持.pem文件导入

如果想直接通过import导入.pem文件内容,需要添加类型声明:

  1. 在项目根目录或src目录下创建declarations.d.ts文件:
declare module '*.pem' {
  const content: string;
  export default content;
}
  1. 在tsconfig.json中确保这个声明文件被包含:
{
  "include": [
    "declarations.d.ts",
    "src/**/*"
  ]
}
  1. 之后就可以直接导入使用:
import cert from './cert.pem';
import key from './key.pem';

const dataServiceTlsSecret = addResource(
    new Secret({
      metadata: {
        name: DATA_SERVICE,
      },
      type: "kubernetes.io/tls",
      stringData: {
        "tls.crt": cert,
        "tls.key": key,
      }
    })
);

注意:如果使用webpack等打包工具,还需要配置raw-loader来加载.pem文件内容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 08:27:25