Raghul SK
Raghul SK

Reputation: 1390

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

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.

Upvotes: 6

Views: 22182

Answers (2)

aris
aris

Reputation: 597

this one working great for me

import * as fs from 'fs';



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

Upvotes: 7

Tim Perry
Tim Perry

Reputation: 13266

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
});

Upvotes: 6

Related Questions