TransWikia.com

How to read the pem file in nodejs?

Stack Overflow Asked by Raghul SK on November 7, 2021

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

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.

2 Answers

this one working great for me

import * as fs from 'fs';



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

Answered by aris on November 7, 2021

You can't require a PEM file - that's only used for JS & JSON files. The error is a complaint that the PEM file is not valid JS syntax.

To read raw data from other files, including PEM, you can use the fs module: https://nodejs.org/api/fs.html.

For example:

const fs = require('fs');

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

Answered by Tim Perry on November 7, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP