简体   繁体   English

如何读取nodejs中的pem文件?

[英]How to read the pem file in nodejs?

Working in the Encode and Decode using the NodeJS, I want to Encode the data using the RS512 algorithm, for using that algorithm I have to pass the secret key as a pem file, so I use require to import that pem file but I cannot able to import that file使用 NodeJS 进行编码和解码,我想使用RS512算法对数据进行编码,为了使用该算法,我必须将密钥作为 pem 文件传递,所以我使用 require 导入该 pem 文件但我不能导入该文件

The Code that I used is我使用的代码是

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

when I import the file like this am getting the error当我像这样导入文件时出现错误

ReferenceError: Invalid left-hand side expression in prefix operation

How to solve this issue.如何解决这个问题。

You can't require a PEM file - that's only used for JS & JSON files.您不能require PEM 文件 - 仅用于 JS 和 JSON 文件。 The error is a complaint that the PEM file is not valid JS syntax.该错误是抱怨 PEM 文件不是有效的 JS 语法。

To read raw data from other files, including PEM, you can use the fs module: https://nodejs.org/api/fs.html .要从其他文件(包括 PEM)读取原始数据,可以使用fs模块: https://nodejs.org/api/fs.html

For example:例如:

const fs = require('fs');

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

this one working great for me这个对我很有用

import * as fs from 'fs';



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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM