【问题标题】:How to read the pem file in nodejs?如何在nodejs中读取pem文件?
【发布时间】:2020-08-04 22:50:31
【问题描述】:

使用 NodeJS 进行编码和解码,我想使用 RS512 算法对数据进行编码,为了使用该算法,我必须将密钥作为 pem 文件传递​​,所以我使用 require 导入该 pem文件,但我无法导入该文件

我使用的代码是

const secretKey = require("./secretkey.pem");

当我像这样导入文件时出现错误

ReferenceError: Invalid left-hand side expression in prefix operation

如何解决这个问题。

【问题讨论】:

    标签: javascript node.js


    【解决方案1】:

    这对我很有效

    import * as fs from 'fs';
    
    
    
    const publicKey = fs.readFileSync("../server/src/config/public.pem", { encoding: "utf8" });
    

    【讨论】:

      【解决方案2】:

      您不能 require 一个 PEM 文件 - 仅用于 JS 和 JSON 文件。错误是抱怨 PEM 文件不是有效的 JS 语法。

      要从其他文件(包括 PEM)读取原始数据,您可以使用 fs 模块:https://nodejs.org/api/fs.html

      例如:

      const fs = require('fs');
      
      fs.readFile("./secretkey.pem", "ascii", function (pemContents) {
        // do whatever you want here
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-10-15
        • 2017-10-31
        • 1970-01-01
        • 2018-06-24
        • 2018-06-04
        • 2014-03-24
        • 2012-08-01
        相关资源
        最近更新 更多