NodeJS Crypto throws “Error: error:1C80006B:Provider routines::wrong final block length”

I am running a MERN app where I store encrypted user data. When retreiving the data, the data should be decrypted.
This is the code that I use for encrypting and decrypting the data

const crypto = require('crypto')

const { SECRET_KEY, SECRET_IV, ENCRYPTION_METHOD } = process.env

if (!SECRET_KEY || !SECRET_IV || !ENCRYPTION_METHOD) {
    throw new Error('secretKey, secretIV, and ecnryptionMethod are required')
}

// Generate secret hash with crypto to use for encryption
const key = crypto
    .createHash('sha512')
    .update(SECRET_KEY)
    .digest('hex')
    .substring(0, 32)
const encryptionIV = crypto
    .createHash('sha512')
    .update(SECRET_IV)
    .digest('hex')
    .substring(0, 16)


// Encrypt data
const encryptData = (data) => {
    const cipher = crypto.createCipheriv(ENCRYPTION_METHOD, key, encryptionIV)
    return Buffer.from(
        cipher.update(data, 'utf8', 'hex') + cipher.final('hex')
    ).toString('base64') // Encrypts data and converts to hex and base64
}

// Decrypt data
const decryptData = (encryptedData) => {
    try {
        const buff = Buffer.from(encryptedData, 'base64')
        const decipher = crypto.createDecipheriv(ENCRYPTION_METHOD, key, encryptionIV)
        const decrypted = decipher.update(buff.toString("utf8"), 'base64', 'utf8') + decipher.final('utf8');
        return decrypted;
    } catch (error) {
        console.error('Decryption Error:', error);
        return null;
    }
}

When I try to decrypt I get the following error

Decryption Error: Error: error:1C80006B:Provider routines::wrong final block length
    at Decipheriv.final (node:internal/crypto/cipher:193:29)
    at decryptData (C:UsersjeshuDesktoppizzahubmiddleWareencrypt.js:35:95)
    at C:UsersjeshuDesktoppizzahubcontrollersorderController.js:101:30  
    at Array.forEach (<anonymous>)
    at findOrderForShop (C:UsersjeshuDesktoppizzahubcontrollersorderController.js:100:16)
    at processTicksAndRejections (node:internal/process/task_queues:96:5) {   
  library: 'Provider routines',
  reason: 'wrong final block length',
  code: 'ERR_OSSL_WRONG_FINAL_BLOCK_LENGTH'
}

what should I do

Unable to send date via postForm in axios

Description of the issue

I am working on a nextjs project. The problem is when I am posting multiple images array via postForm is not working but if I use postForm.append then those image arrays are working properly.

axios version : “1.6.1”,

This is an example of posting via Axios postForm

   images: [File, File, File]
   const res= await axios.postForm("/example",images)

This is Example of posting old process

const postForm = new FormData();
   images.forEach((img) => {
      postFrom.append("images", img);
    });

How to solve this problem.

Typescript JSDoc comments not showing up in intellisense in vscode

I have a javascript codebase, where i am adding type definitions so that VSCode intellisense can help with the types and descriptions, even in js files. I have not been able to get my JSDoc comments to show up in the js file though, even though the types show up correctly.

TRY 1

interface RunFunction {
  /**
   * @param argv arguments passed from command line
   * @param config global config
   * @returns void
   */
  (
    argv: typeof import('./index.js').argv,
    config: typeof import('./index.js').config,
  ): void;
} 

TRY 2

/**
 * @param argv arguments passed from command line
 * @param config global config
 * @returns void
*/
interface RunFunction {
  (
    argv: typeof import('./index.js').argv,
    config: typeof import('./index.js').config,
  ): void;
} 

TRY 3

interface RunFunction {
  (
    /** arguments passed from command line */
    argv: typeof import('./index.js').argv,
    /** global config */
    config: typeof import('./index.js').config,
  ): void;
} 

I have also tried different combinations of the above. But when i try to use it in a js file, although I do see the types being correctly suggested, i don’t see the comments / description at all.

This does not seem to work in TS playground as well, so it might very well be a limitation of JSDoc implementation in TS and not a limitation of VScode or the project configuration.

Is there another way to define these types so that the comments / description show up properly in intellisense?

Two base values of x-axis

I am trying to evaluate the bar chart . I need x-axis base value like below.

Sun Mon Tue Wed Thurs Fri Sat
09 10 11 12 13 14 15

Two bases value of x-axis.
I am echarts ,but i am unable get the values above i mentioned. Please give me suggestions to get off this problem

Rendering Lag Issue in Firefox Browser

enter image description hereThe page is normal in the Chrome browser. However, in the Firefox browser, after scrolling multiple times over a period, the page experiences rendering lag. The page data is loaded, so I’m certain it’s not a network issue. In what aspects should I investigate this problem?

enter image description here

is this normal? the cpu usage seems pretty high

Encapsulating part of JS code so it isnt shown by the programmer tools of a web browser

I want to connect to a SQL Database through JS and a ActiveXOBject object.However since the code every website can be found by the web browser which is running a website , this means that the credentials for access of the SQL Server will be available to anyone.

Obviously for security reasons you dont want this,so is there a way to encapsulate those data?Thanks!

I cannot find this actual code in my react app source file anywhere but in browser DOM. I want to remove it

Screenshot

I cannot find this div anywhere in app source and also because of it I am having css isuees.

remove it. so that I can have my expected css working.

body {
  margin: 0;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
    'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
    sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  background: rgb(198, 0, 110);
  background: radial-gradient(circle, rgba(198, 0, 110, 1) 0%, rgba(3, 18, 37, 1) 100%) !important;
}

background property not working.

How to tell if PM2 is running

I am at the very start of JS learning.
I connect to Ubuntu 20.04 virtual machine via macOS terminal. It runs backend on Express JS.
I want to know if PM2 is running.
I can type pm2 monit, but I don’t know if this command starts pm2 or shows status.

I tried to google the topic, but it confused me.
I tried ps -la, bit I didn’t see pm2 even when it was running.

I tried pm2 kill first to make sure that pm2 is not running, then pm monit. I expected pm monit not to work, but it did worked, though it didn’t have a process in list.

is it possible to show case in javascript? [closed]

eveytime i need to update if elseif to update when something has changed..

function (a,b,c,d) {
if (!a && !b) {
            var x = c + d + 'helloword';
        } else if (!a) {
            var x = b + c + d + 'helloword';
        } else {
            var x = a + b + '.' + c + d + 'helloword';
        };
//what i want is:
 var x = if(a) + if(b) + if(c) + if(d) + 'helloword';
}

what i want to do is:

function (a,b,c,d) {
 var x = if(a) + if(b) + if(c) + if(d) + 'helloword';
}

is it possible of coding it easly?

How to use font-family in jspdf

In CSS, we can use font-family to render multi fonts, for example:

font-family: Roboto, ZhiMangXing;

If Roboto not support, browser will use ZhiMangXing to render the text;

But in jsPDF, we can only use setFont api, not font-family;
Is it possible to use font-family in jspdf?
Or is there any hack method to do that?

This is my demo
https://codesandbox.io/s/stoic-firefly-jpqtld?file=/public/index.html

In this demo, the webpage render the text correctly with css
The two button download the pdf, but have some font problem

I have tried pdfmake, no luck

How can I change the color of multiple specific words in a string? (JS/HTML/CSS/jQuery)

I’m trying to create a function that can read through large a string of text, automatically detect key words, and then change the color of these individual words. For example, in the sentence, “he walked to the store and then he walked to his house,” I want the function to individually detect the word “he” and change the text color to green, while also detecting the word “walked” to change the text color to red without altering the rest of the sentence. This would be on a much greater scale with more key words and colors.

I’ve gotten to the point where I can get my program to detect certain words in a string of text written in a or , but when I attempt to change the color of the words through there, it changes the color of all of the words in the string (by altering the css), which isn’t what I want. I also got it to change the individual word within a , but it changed the words within other sections as well.

I’m also having difficulty getting it to change the different key words, for example when it uses the color green for “walked” when it should actually be red. I don’t want to manually use around every single word, so I would like to find a way to do this automatically.

I appreciate any assistance, thank you!

Nuxt 3 SSR: useFetch() or useAsyncData returning null on page refresh

Please help me. I have Nuxt 3 project which I need SSR. This is a new generate project, which I didn’t change any default config other than stated in here. I’m using composition API.

Here is the Vue & config file

test.vue

<template>
    <div>
        <NuxtLink to="/">balik</NuxtLink>
        <p>{{data}}</p>
    </div>
</template>

<script setup lang="ts">
const fullUrl = "https://fakestoreapi.com/products"
const data = ref({})

onMounted(async () => {
    data.value = await useFetch(fullUrl, {
        server: true,
        immediate: true 
    });
    console.log("mounted", data.value);    
})

onServerPrefetch(async () => {
    data.value = await useFetch(fullUrl, {
        server: true,
        immediate: true
    });
    console.log("server", data.value);
    console.log("************************");
})

data.value = await useFetch(fullUrl, {
    server: true,
    immediate: true
});
console.log("======================");
console.log("setup", data.value);
</script>

nuxt.config.ts

export default defineNuxtConfig({
    routeRules: {
        "/test": { ssr: true }
    }
})

Here is the console from server

setup {
  data: RefImpl {        
    __v_isShallow: false,
    dep: undefined,      
    __v_isRef: true,     
    _rawValue: null,
    _value: null
  },
  pending: RefImpl {
    __v_isShallow: false,
    dep: undefined,
    __v_isRef: true,
    _rawValue: false,
    _value: false
  },
  error: ObjectRefImpl {
    _object: { gE1Y7EtyZS: [H3Error] },
    _key: 'gE1Y7EtyZS',
    _defaultValue: undefined,
    __v_isRef: true
  },
  status: RefImpl {
    __v_isShallow: false,
    dep: undefined,
    __v_isRef: true,
    _rawValue: 'error',
    _value: 'error'
  },
  execute: [Function (anonymous)],
  refresh: [Function (anonymous)]
}
server {
  data: RefImpl {
    __v_isShallow: false,
    dep: undefined,
    __v_isRef: true,
    _rawValue: null,
    _value: null
  },
  pending: RefImpl {
    __v_isShallow: false,
    dep: undefined,
    __v_isRef: true,
    _rawValue: false,
    _value: false
  },
  error: ObjectRefImpl {
    _object: { gE1Y7EtyZS: [H3Error], uD8NPFvkOs: [H3Error] },
    _key: 'uD8NPFvkOs',
    _defaultValue: undefined,
    __v_isRef: true
  },
  status: RefImpl {
    __v_isShallow: false,
    dep: undefined,
    __v_isRef: true,
    _rawValue: 'error',
    _value: 'error'
  },
  execute: [Function (anonymous)],
  refresh: [Function (anonymous)]
}

The problem is everytime I refresh the page, I only get null data. But if I change page from / to /test, it work. I also tried to disable ssr from routeRules, it work, but I need ssr to be true.

I already read from this stack overflow question from here, but none of them work.

What I have done:

  • Change to data.value = await useAsyncFetch("products", () => $fetch(fullUrl)) in all useFetch
  • Update nodejs to v18 (I tried v18.13 and 18.18.2)
  • Update nuxt to latest (“nuxt”: “^3.8.1”)
  • Change to node 16 (because from the previous article some said that change to node 16 helped)
  • Tried nextTick, only worked on client side. I need it on server side.

Am I missing something in here? Or is there any tutorial using ssr to fetch data, because as long as I find tutorial they always either ssr: false or it’s just the code and when I tried the same code it didn’t work. Or is this unresolved issue from Nuxt 3?

Note: I will add param to refetch the data.

Javascript – Label selector

Below is an html and Js code that has a list of devices with name and label. I have a drop down menu which is populated with names and an event listener which returns the associated label.

What could be the possible issue?

I am new to javascript and html coding. Apologies if it is a noob question.

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Device Selector</title>
</head>

<body>

    <label for="labelSelector">Select Device:</label>
    <select id="labelSelector">
        <option value="">Select device</option>
    </select>

    <script>
        const deviceListArray = [
            { createdTime: 1691728083163, name: 'name1', label: 'label 1' },
            { createdTime: 1691725209793, name: 'name2', label: 'label 2' },
            { createdTime: 1691710614954, name: 'name3', label: 'label 3' }
        ];

        const labelSelector = document.getElementById('labelSelector');

        // Populate the drop-down menu with all the labels/names
        deviceListArray.forEach(entry => {
            const option = document.createElement('option');
            option.value = entry.label;
            option.text = entry.label;
            labelSelector.add(option);
        });

        // Event listener for when a label is selected
        labelSelector.addEventListener('change', handleLabelSelection);
        let selectedDeviceID;
        let deviceIDSelected;
        function handleLabelSelection(event) {
            const selectedLabel = event.target.value;
            const selectedDevice = deviceListArray.find(entry => entry.label === selectedLabel);
            if (selectedDevice) {
                selectedDeviceID = selectedDevice.name; // Corrected property name to 'name'
            } else {
                console.log('Device not found for the selected label');
            }

            // Call a function to perform actions with the updated selectedDeviceID
            performActionsWithDeviceID(selectedDeviceID);
        }

        // Function to perform actions with the updated selectedDeviceID


        function performActionsWithDeviceID(deviceID) {
            deviceIDSelected = deviceID;
        }

        console.log(deviceIDSelected);

    </script>

</body>

</html>```


Issue is I am unable to log the associated label outside of the function although I have declared it globally.