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 functionality of Skrollr on mobile is currently not working properly due to the inability to prevent default actions

Encountering the following error on all chromium browsers while using the Skrollr library and accessing the website through mobile: "[Intervention] Unable to preventDefault inside passive event listener due to target being treated as passive. See < ...

What is the process for assigning an element to a specific URL ID?

Imagine having an array of objects structured like this: [{ details: {id: 7}, type: minigame1, ...(more values that need to be accessed later) }, { details: {id: 8}, type: minigame1, ...(more values that need to be accessed later) }, { details: {id: ...

What is the best way to ensure an observable has been updated before proceeding with additional code execution?

Is an observable the best choice for providing live updates of a variable's value to another class? I have a loop in my service class that looks like this: elements.forEach(element => { doStuff(); this.numberSubject.next(valueFromDoStuff); }) ...

Issues with the functionality of the shopping cart are causing a disruption

This is the coding for the online shopping cart: <!DOCTYPE html> <html lang="en-us"> <head> <meta charset="UTF-8" /> <title>Online Shopping Cart</title> <script src="jquery-3.1.1.min.js"></script> ...

The error message thrown is: "TypeError - attempting to call an undefined function

I'm new to working with node and express, and I encountered an error when running my App. Does anyone have any solutions? I suspect the error may be in this line "app.use(express.static(user));" but I'm not certain. var express = require('e ...

Enforce the splicing of the ng-repeat array with the utilization of track by

Our app incorporates a task list that can potentially grow to a substantial size. The main task list is accompanied by a sidebar, where selected tasks can be edited using a different controller (TasksSidebarCtrl instead of TasksCtrl which handles the list ...

Determining which data is retrieved from a database based on a specific field using Sequelize and MySQL

I'm looking to retrieve the most recent records from a database, organized by category. My goal is to fetch 20 records, with 5 of the latest posts in each category. I want to ensure that the result consists of 20 total records, evenly distributed amon ...

Tactics for developing an intricate AJAX and jQuery form with nested components

We have a complex form to construct that will allow the creation or updating of multiple instances of entity A, where each instance of entity A can have multiple instances of entity B. Both types of entities are intricate with many fields and dropdowns, b ...

Unable to retrieve JSON data from converting TXT using JavaScript, resulting in undefined output

After converting txt to JSON, I encountered an issue. const txt = JSON.stringify(`{ ErrorList: [{ 80: 'Prepared' }], Reference: [ { 'Rule Name': 'Missing 3', 'Rule ID': 1, 'Rule Des& ...

Unable to navigate a simulated scrollbar

As someone who is new to web development, I am embarking on the journey of building a UI Grid that can effectively display a large amount of data. My goal is to implement a scrollbar that allows for horizontal scrolling across approximately 1,000,000 data ...

Retrieving data from Ajax and passing it to PHP

I am currently facing an issue with my Ajax code. When I try to access a textfield variable in PHP after alerting the value successfully, I receive an error stating Undefined index. Javascript Code <SCRIPT> function sendData(UserID) { var name = en ...

issue with scrolling using the ideal scrollbar

Can someone help me figure out how to integrate the 'perfectScrollbar('update')' function with my Angular.js code? $http.get('demo/json/test.json'). success(function(data, status, headers, config) { $scope.items = d ...

Concealing div containers and eliminating gaps

Looking for a way to filter div boxes using navigation? Check this out: <ul> <li><a href="javascript:void(0);" data-target="apples">Appels</a></li> <li><a href="javascript:void(0);" data-target="bananas">Ban ...

Assign a unique HTML attribute to a child element within a Material-UI component

Currently, I am trying to include the custom HTML5 attribute "data-metrics" in the span element within the ListItemText Material UI component. However, I am facing some difficulty achieving this as per the specifications outlined in the Component API Docum ...

In JavaScript, the checkboxes in all columns of a table with over 200 rows can be set, but only the checkboxes in the rows

Seeking help to implement toggle buttons for checkboxes on a page with a large table fetched from an external system. The table can have over 200 rows or more. Currently, I am facing an issue where I can only access and manipulate the visible checkboxes o ...

What could be the reason for the HTML canvas not displaying anything after a new element is added?

How come the HTML canvas stops showing anything after adding a new element? Here is my HTML canvas, which works perfectly fine until I add a new element to the DOM: <canvas class="id-canvas", width="1025", height="600"> ...

Ways to acquire dynamic content without relying on Remark/Grey Matter

In my stack of technologies, I am using nextJS with react and typescript. While I have successfully set dynamic routes for my blog posts, I am now facing a challenge in creating pages that do not rely on markdown. Despite searching extensively for code exa ...

Using a regular div to display a modal - Reactstrap

Exploring the possibilities with a Reactstrap Modal: Modal - Reactstrap I am curious about integrating this modal seamlessly into a page layout, similar to a regular div. For example, having the modal display on the page without the animation effects and ...

Issue with the DocPad plugin for Gulp

I'm encountering an issue while trying to utilize the gulp docpad plugin. When I run docpad run, the following error message is displayed: Error: spawn UNKNOWN at exports._errnoException (util.js:837:11) at ChildProcess.spawn (internal/child_process. ...

Identifying the issue of body.onload not being triggered

My web pages use body.onload (or window.onload) to properly set up, but sometimes the onload event is not being triggered. Is there a way in a specific web browser (preferably Chrome, where this issue seems more common) to identify what is causing the pag ...