Storing a byte array in a local file using JavaScript: A Step-by-Step Guide

Recently, I encountered an issue while working with an openssl certificate. Specifically, when I tried to download the certificate from my API, it returned byte arrays that I needed to convert to a PEM file in order to access them through another API.

The raw byte array format looked something like this:

0
g0
'   *H


0

However, when I downloaded the certificate via Postman, the byte array appeared slightly different:

0‚
g0‚
'   *†H†÷
 ‚
‚
0‚

This discrepancy led to errors during conversion to a PFX file format, as the other API threw the following error message:

DecodeToAsn:
            ASN.1 length cannot be more than 4 bytes in definite long-form.
            This error typically occurs when trying to decode data that is not ASN.1
            A common cause is when decrypting ASN.1 data with an invalid password,
            which results in garbage data. An attempt is made to decode the garbage bytes
            as ASN.1, and this error occurs...
          --DecodeToAsn
          Failed to decode PFX ASN.1 for integrity verification.

Now, the challenge lies in correctly storing the byte arrays into a local file or finding a way to convert them to match the format obtained through Postman. Currently, my code writes the bytearray directly to a file using the following function:

async function downloadCertificate() {
    try {
        let pfx = new chilkat.Pfx();

        let downloadedPfxByteArray = await Api.downloadCertificate(id);
        let pfxFileLocation = `${process.cwd()}\\media\\CERTFILE.pfx`;

        fs.writeFileSync(pfxFileLocation, downloadedPfxByteArray);

        pfx.LoadPfxFile(pfxFileLocation, 'password');
        let strPem = pfx.ToPem();

        console.log(strPem);

        return pemValue;
    } catch (error) {
        console.log(`READ PFX FAIL ! ${error}`);
    }
}

If anyone has insights or solutions on how to resolve this issue, your help would be greatly appreciated. Thank you for taking the time to read!

Answer №1

#!/usr/bin/env node
const fetch = require('node-fetch');
const fs = require('fs').promises;

async function downloadFile() {
    await fs.writeFile(
        '/tmp/so-58603015.pfx',
        Buffer.from(await (await fetch('…url…')).arrayBuffer())
    );
}

downloadFile();

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The module is missing a declaration file and therefore has an implicit type of 'any'. This error (TS7016) occurs in TypeScript version 2.0

So I've been experimenting with the module react-image-gallery. Surprisingly, there seems to be no types available for this package when trying to install it using npm. When attempting npm install @types/react-image-gallery, all I get is a 404 error. ...

Code is not running in ReactJS

My challenge is to use canvas and script to draw a rectangle with one diagonal line. However, when I try to do so, only the rectangle appears on my browser. It seems like the script is not being executed. Here's the code: import React, { Component } ...

Retrieving data using a class in an AJAX form submission

I am attempting to use AJAX to submit an HTML form. Here is my HTML: <form class="lyrics"> <input type="text" value="" id="song" name="song"> <button type="submit" class="btn btn-info lirik">lyrics</button> </form> ...

Tips for displaying a jQuery error message when a key is pressed

I am working with a textarea that has a word count limit of 500. I need to display an error message below the textarea if the word count exceeds 500. I have successfully calculated the word count, but I am unsure how to display the error message and preve ...

Can we define the input and return types for functions using httpsCallables?

I have implemented a callable function in my app to update user claims. The functions are written in Typescript and I have used an interface to define the required data shape for the function. My objective is to make it easier for any developer on the tea ...

What could be the reason for my React Component not properly associating with the image?

The title appears to be correctly displayed, but there seems to be an issue with the images. I've thoroughly reviewed the code multiple times, but unfortunately, I'm unable to identify the problem. Please provide guidance on what changes need to ...

D3 circle packing showcases a concise two-line label text

I've browsed through the topics on this site, but none of the solutions provided worked for my issue. Is there a way to display text in two lines for long texts in D3 circle packing? The following code is what I am using to show labels on circles: c ...

How can I transfer an image from the clipboard onto a fabric.js canvas?

I am currently working on developing a function that will allow users to paste an image from their clipboard onto a canvas as a new fabric.Image(). However, every search result I come across either discusses cloning existing objects within the canvas or pa ...

Exploring Angular 2's nested navigation using the latest router technology

Is there a way to implement nested navigation in Angular? I had this functionality with the previous router setup. { path: '/admin/...', component: AdminLayoutComponent } It seems that since rc1 of angular2, this feature is no longer supported. ...

Issue with retrieving URL parameters in Nextjs during server side rendering

Currently, I'm attempting to extract the request query, also known as GET parameters, from the URL in server-side rendering for validation and authentication purposes, such as with a Shopify shop. However, I am facing issues with verifying or parsing ...

Unexpected behavior encountered when running Angular 8 radio button checked function

I have an Angular 8 web app with some unique logic implemented as shown below: HTML: <div *ngFor="let item of selectedItems;"> <input type="radio" [(ngModel)]="mySelectedItem" [value]="item.key" (ngModelChange)="setCh ...

The app.get() method in Node JS and Express requires three parameters, and I am seeking clarification on how these parameters work

Hey there, I'm new to this and have a question regarding my code using passport-google-oauth20. app.get('/auth/google/secrets', passport.authenticate('google',{failureRedirect: '/login'}), function(req,res){ res.redirec ...

Looping Feature in Ionic Framework's Slides Component

Currently, I am working on developing an application using Ionic-Angular. When it comes to incorporating slides in my app, I opted for the ionic 4 ion-slides component. Everything was going smoothly until I wanted to enable looping for the slides so that u ...

Looking for guidance on implementing explicit waits in Protractor for non-angular applications

I have noticed that automating non-angular applications with Protractor can be challenging. Currently, I am using some methods to add an explicit wait to my existing Serenity click and enter functions. However, I am curious if there is a way to automatic ...

Send form data without reloading the page and connect it to a JavaScript script

I've designed a system that reveals values based on a specific input selection. Below is the main form where users can enter model numbers and press enter: <form> <input type="text" name="ModNum" id="ModelNumber" pattern="^PIV13RT[23]?$" ...

Challenges with Angular observables

Struggling to make observables work has been quite the challenge for me lately. My code now resembles a chaotic battleground rather than the organized structure it once was. The dreaded "ERROR TypeError: Cannot read property 'map' of undefined" ...

Retrieving the Object value in Primeng p-dropdown when there is a change in selection

In my p-dropdown, I am trying to extract the selected value. <p-dropdown optionLabel="name" [options]="things" placeholder="Select Thing" [(ngModel)]="input" (onChange)="getValue(input)"></p-dropdown> typescript: //each lin ...

I am unfamiliar with this specific JavaScript algorithm problem from Codewars

I need help with a JavaScript algorithm question This problem involves extracting two letters from the middle of odd-numbered characters My confusion lies in function getMiddle(s) { //Code goes here! let answer = ""; if (s.length % 2 !== 0) { a ...

The messageReactionAdd event has suddenly stopped functioning without any explanation

Currently, I am developing a Discord bot that assigns the role "Voteur" to a user when they react to an embed message created by the bot. Everything was functioning perfectly until recently, but for some reason, it has stopped working. The bot successfull ...

How to display and retrieve data from a JSON object using JavaScript

Having trouble retrieving input values from a JSON object and getting 'undefined' when running the code. Any suggestions or ideas would be greatly appreciated as I have tried various approaches. Additionally, I need to utilize JSON for my school ...