Exiting / cancel rest of the Promise handling

I was reading some posts and got similar question in interview. Lets say the code snippet looks like this:

const newPromise = new Promise((resolve, reject) => reject());

newPromise
  .then(() => { console.log("1") })
  .catch((error) => { console.log("2"); })
  .then(() => { 
      console.log("3"); 
      throw new Error; 
  })
  .then(() => console.log("4"))
  .catch(() => console.log("5"))
  .catch(() => console.log("6"))

So by looking at this, my first thought was that since the Promise “instantly” rejects, it will look for the closest catch, handle the “error” and exit the Promise cycle.

As it turns out there are 2 scenarious what can happen after that catch method:

  1. If it handles the error or you call Promise.resolve(), then the Promise switches back to fullfilled state and it will look for the first then method.
  2. If it rethrows the errors or you call Promise.reject() it will propogate the error, promise stays in the rejection state and it will look for the closest catch method.

So my question is – how can we simple exit / terminate the Promise process from either then or catch callbacks, if we end up in this “callback hell” scenario?

What I tried:

Without returning anything, it goes to fulfill state, which means nearest then is executed.

Then I tried to simply return any value, it results in Promise going in to “fulfill” state.

Then I tried either Promise.reject() or Promise.resolve() – same result as above respectively.

How can I detect if some application/software/tools is set to always on top using Node.js

I want to create tracking software, which can track which application/software/tools is open currently. Basically I want to get current Active Window. In case If you have multiple screens then I want to get current active window in both the screens.

I also want to check if there’s any software/tools running which keeps some software always keep on top, if possible.

How can I achieve this using Node.js.

Is there any specific library available for this?

I tried some low level C++ Code and compile it using node-gyp and ran it. I was able to get current active window, but it is only for single screen, What if I have multiple screen and two different program is opened in those screen? I want those two programs.

Here’s C++ Code:

addon.cc file

#include <napi.h>
#include <windows.h>
#include <Psapi.h> 

Napi::Object GetActiveWindowInfo(const Napi::CallbackInfo& info) {
    Napi::Env env = info.Env();

    HWND hwnd = GetForegroundWindow();
    const int nMaxCount = 256;
    TCHAR szWindowTitle[nMaxCount];
    DWORD pid;

    // Retrieve the window title
    GetWindowText(hwnd, szWindowTitle, nMaxCount);

    // Retrieve the process ID (PID) of the active window
    GetWindowThreadProcessId(hwnd, &pid);

    // Get the process handle using the PID
    HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, pid);

    TCHAR szProcessName[MAX_PATH] = TEXT("<unknown>");
    if (hProcess != NULL) {
        // Retrieve the process name
        GetModuleFileNameEx(hProcess, NULL, szProcessName, MAX_PATH);
        CloseHandle(hProcess);
    }

    // Construct the return object
    Napi::Object result = Napi::Object::New(env);
    result.Set("title", Napi::String::New(env, szWindowTitle));
    result.Set("processName", Napi::String::New(env, szProcessName));

    return result;
}

Napi::Object Init(Napi::Env env, Napi::Object exports) {
    exports.Set("getActiveWindowInfo", Napi::Function::New(env, GetActiveWindowInfo));
    return exports;
}

NODE_API_MODULE(addon, Init)

binding.gyp file

{
  "targets": [
    {
      "target_name": "addon",
      "sources": [ "addon.cc" ],
      "include_dirs": [
        "<!@(node -p "require('node-addon-api').include")"
      ],
      "cflags!": [ "-fno-exceptions" ],
      "cflags_cc!": [ "-fno-exceptions" ],
      "defines": [
        "NAPI_CPP_EXCEPTIONS" 
      ],
      "libraries": []
    }
  ]
}

app.js file

const addon = require("./build/Release/addon.node");

setInterval(() => {
  const windowInfo = addon.getActiveWindowInfo();
  console.log("Window Title:", windowInfo.title);
  console.log("Process Name:", windowInfo.processName);
}, 1000);

package.json file

{
  "name": "addon",
  "version": "1.0.0",
  "description": "Node.js addon",
  "main": "addon.cc",
  "scripts": {
    "build": "node-gyp configure build"
  },
  "dependencies": {
    "node-addon-api": "^8.0.0"
  }
}

How to Run

npm install

npm run build

node app.js

“Undefined array key” When passing post data to php script

Very stuck. I have some JS that passes a start and end date from a form to a php file that then selects the entries of that date range in the DB and exports an Excel file. The ‘date’ is correct, and as far as I can tell ‘data’ is set correctly in Ajax. But when I check the apache_error.log,

I’m getting:

PHP Warning: Undefined array key “startDate”

PHP Warning: Undefined array key “endDate”

    $(document).on('submit', '#export_form', function(event){
        event.preventDefault();
        //this returns correct date 2024-05-01
        console.log($("#startDate").val());
        $.ajax({
            url: 'exporttoexcel.php',
            type: 'POST',
            data: { startDate: $('#startDate').val(), endDate: $('#endDate').val() },
            processData: false,
            xhrFields: {
            responseType: 'blob' // to avoid binary data being mangled on charset conversion
                },
            success: function(blob, status, xhr) {
                    // check for a filename
                    var filename = "";
                    var disposition = xhr.getResponseHeader('Content-Disposition');
                    if (disposition && disposition.indexOf('attachment') !== -1) {
                        var filenameRegex = /filename[^;=n]*=((['"]).*?2|[^;n]*)/;
                        var matches = filenameRegex.exec(disposition);
                        if (matches != null && matches[1]) filename = matches[1].replace(/['"]/g, '');
                    }

                    if (typeof window.navigator.msSaveBlob !== 'undefined') {
                        // IE workaround for "HTML7007: One or more blob URLs were revoked by closing the blob for which they were created. These URLs will no longer resolve as the data backing the URL has been freed."
                        window.navigator.msSaveBlob(blob, filename);
                    } else {
                        var URL = window.URL || window.webkitURL;
                        var downloadUrl = URL.createObjectURL(blob);

                        if (filename) {
                            // use HTML5 a[download] attribute to specify filename
                            var a = document.createElement("a");
                            // safari doesn't support this yet
                            if (typeof a.download === 'undefined') {
                                window.location.href = downloadUrl;
                            } else {
                                a.href = downloadUrl;
                                a.download = filename;
                                document.body.appendChild(a);
                                a.click();
                            }
                        } else {
                            window.location.href = downloadUrl;
                        }

                        setTimeout(function () { URL.revokeObjectURL(downloadUrl); }, 100); // cleanup
                        $('#export_form')[0].reset();
                        $('#exportModal').modal('hide');
                    }
                }

        })

        //window.open('exporttoexcel.php');
        //document.getElementById('export_form').submit();
        if(startDate != '' )
        {
            //window.open('exporttoexcel.php', '_blank');
        }
        else
        {
            alert("Fields are Required");
        }
    });
<?php
include('db.php');
include('function.php');
include('PhpXlsxGenerator.php'); 
//error_reporting(E_ALL); 
//ini_set('display_errors', 1);
$start_date = $_POST['startDate'];
$end_date = $_POST['endDate'];


$sql = "SELECT r.id,
r.created_at AS 'Date Time', ...irrelevant
?>

Why is the post-data not being passed along?

Trying to hide an element using tempermonkey userscript

Objective

I am trying to hide an element using Temper Monkey user script

The testing webpage is https://www.dmla5.com/play/8733-1-5.html.

My goal is to have the loaded progress bar (below the video) hidden after clicking the pink button.


Simplified version that sums up the objective

document.getElementsByClassName("leleplayer-bar")[0].hidden = true;

Code

The element is loaded after a button click, so I had to add delays.

Currently, it works when directly pasted into the Google Chrome dev console but doesn’t work as a user script, please take a look at my code

// ==UserScript==
// @name         Hide leleplayer-bar
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  Hides elements with class leleplayer-bar
// @author       Your name
// @match        */*/*
// @grant        none
// @run-at       document-start
// ==/UserScript==

(function() {
    function hideElement() {
        var elementsToHide = document.getElementsByClassName("leleplayer-bar");
        if (elementsToHide.length != 0) {
            var elementToHide = elementsToHide[0];
            console.log("Target element found. Hiding...");
            elementToHide.hidden = true;
            console.log("Element hidden successfully.");
            return 1;
            console.log("Observation stopped.");
        } else {
            console.log("Target element not found.");
        }
        return 0;
    }

    function observeDOM() {
        var targetNode = document.body;
        var config = { childList: true, subtree: true };

        var observer = new MutationObserver(function(mutationsList, observer) {
            for (var mutation of mutationsList) {
                if (mutation.type === 'childList') {
                    if (hideElement() === 1) {
                        observer.disconnect();
                        return;
                    }
                }
            }
        });

        observer.observe(targetNode, config);
    }

    setTimeout(function() {
        if (hideElement() === 0) {
            observeDOM();
        }
    }, 1000);
})();

Unable to find VUE folder in starport project

I am new to blockchain and recently started using starport to set up my first project. As a part of starport their is supposed to be a a folder vue for running a interface for interacting with the chain, However I am unable to find this folder in my directory, how do I obtain this?enter image description here

I tried to check the version of starport and it is up to date.

In angular 16 error occured after implement the CSP (Content Security Policy)

I am facing an issue regarding the CSP (Content Security Policy) recently implemented in our project using Ngnix in angular 16. I have tried many solutions but still, the issue is not resolved. If anyone knows how to fix this issue let me know.

Some of the libraries are used in our project and they create some inline styles and elements automatically on the runtime browser

angular-split, angular-material

Console error:

Refused to apply inline style because it violates the following Content Security Policy directive: “style-src ‘self’ ‘nonce-8c65b1e1638652932ecdc7c995347a95′”. Either the ‘unsafe-inline’ keyword, a hash (‘sha256-biLFinpqYMtWHmXfkA1BPeCY0/fNt46SAZ+BBk5YUog=’), or a nonce (‘nonce-…’) is required to enable inline execution. Note that hashes do not apply to event handlers, style attributes, and javascript: navigations unless the ‘unsafe-hashes’ keyword is present.

Below are the approaches that I have already tried.

https://content-security-policy.com/examples/allow-inline-st...

https://blog.stackademic.com/whats-a-nonce-7508458bded9

https://dev.to/ferdiesletering/how-to-implement-an-inline-st...

https://github.com/ferdiesletering/angular-csp-nonce

I use the TABULATOR library, but the clear button on the list editor does not appear

I use the TABULATOR library, but the clear button on the list editor does not appear.

I am developing a website through Microsoft’s power pages. In the power pages, to manipulate dom, a click button or table has to be created only by using the jquery document ready method. Is it a problem that I cannot create dom because I put it in the document ready method?

Please help me

 $(document).ready(async function() {

    let initDutyDescList = await getDutyDescList(); //get data from sever

    var table = new Tabulator("#dutyDescTable", {
        height: 300, // 테이블 높이 설정
        data: initDutyDescList, // 데이터 배열
        layout: "fitColumns",  // 열이 테이블에 맞게 조정
        movableColumns: true, // 열을 드래그하여 옮길 수 있도록 설정
        rowSelection: "checkbox", // 각 행에 체크박스 추가
        downloadConfig :{ 
            columnGroups : false , //다운로드한 테이블의 열 헤더에 열 그룹을 포함하지 않음 
        },
        columnHeaderVertAlign:"middle",
        columns: [ // 테이블 열 정의
        {
            formatter:"rowSelection", titleFormatter:"rowSelection", hozAlign:"center", 
            headerSort:false, width:30, headerHozAlign: "center"
        },
        {
            title:"No.", formatter:"rownum"
            , width:35 
            , headerSort:false,
        },
        {
            title : "업무기술서",
            headerHozAlign: "center",
            columns : [
            {
                title: "활동주기",
                field: "icfr_activity_cycle_formattedValue",
                editor: "list", // 'editor' 속성에 'list' 에디터 설정
                editorParams: {
                  values: ["일", "월", "발생시", "분기", "반기"],
                  clearable: true, // 'clearable' 옵션을 'editor' 속성에 직접 설정
                  listOnEmpty: true,
                },
              },

            ]
        }  
        ]
      });
    });

I tried customizing it, but it wasn’t satisfactoryㅇ

Can a Next.js Application be Bundled into a Single JavaScript File for Integration into an External HTML Page?

I am currently working on integrating a Next.js application into an existing HTML page. My objective is to render Next.js components within this HTML page by importing a JavaScript file (generated from the Next.js application) into a tag. But, alternative approach is also fine.

Is it possible to bundle the Next.js app into a single JavaScript file?

I have tried the Next.js export feature, however, it doesn’t bundle everything into a single file. I’m unsure how to proceed with rendering the application in an HTML page.

Any insights, recommendations, or alternative approaches would be greatly appreciated.

Thank you in advance for your assistance!

convert csv file into json format using javascript

The below is my Javascipt code to convert my csv file into json format. It works fine but the issue is when i upload a csv file for the first time, it will not work. It starts working from the 2nd time. It might be because it needs time to read the file. but i used async await also. But the issue is still there

// Function to handle file upload and convert CSV to array
async function handleFileUpload(file) {
  if (!file || !file.type.startsWith('text/csv')) {
    console.error('Error: Invalid file type. Please upload a CSV file.');
    return; // Exit if not a CSV file
  }
  
  const reader = new FileReader();
  const csvData = await readFileAsText(reader, file);
  
  const lines = csvData.split('n'); // Split CSV into lines
  // Create an empty array to store the parsed data
  const parsedData = [];
  // Loop through each line (except the header)
  for (let i = 1; i < lines.length; i++) {
    // Split the line into cells using comma as delimiter
    const cells = lines[i].split(',');
    // Assuming the first line is the header, create an object from cells
    const rowObject = {};
    for (let j = 0; j < cells.length; j++) {
      // Remove extra spaces and quotes from cell values
      rowObject[`Field ${j + 1}`] = cells[j].trim().replace(/^"|"$/g, '');
    }
    // Add the object to the parsedData array
    parsedData.push(rowObject);
  }
  console.log('Parsed data:', parsedData); // You can use this data for Bubble list
  // Optionally, set the parsed data to a Bubble element (replace "your_list_element" with the actual element ID)
  bubble_fn_returnformattedtext(JSON.stringify(parsedData));
}

// Function to read file as text using FileReader
function readFileAsText(reader, file) {
  return new Promise((resolve, reject) => {
    reader.onload = function(event) {
      resolve(event.target.result);
    };
    reader.onerror = function(event) {
      reject(event.target.error);
    };
    reader.readAsText(file);
  });
}

// Event listener for file upload button (replace "file_uploader" with the actual element ID)
document.getElementById('fileid').addEventListener('change', async function(event) {
  const uploadedFile = event.target.files[0];
  await handleFileUpload(uploadedFile);
});

`

Why I can’t fetch my data from my database in NextJs Prisma using server side

so I have previous fetch from database and it’s working properly fine, but when I tried to fetch a single data from my database, I get this

Warning: Cannot update a component (Router) while rendering a
different component (EventPageDetail). To locate the bad setState()
call inside EventPageDetail, follow the stack trace as described in
https

So what I did here is, I created a page, and then call the component and then call the server-action

app/events/[eventId]/page.tsx

const EventDetailPage = () => {
  return (
    <>
        <EventPageDetail />
    </>
  )
}

components/admin/admin-events-detail.tsx

"use client";

import { getDataById } from "@/data-query/appointment";
import { useParams } from "next/navigation";
import React from "react";

export default  function EventPageDetail() {
  const { eventId } = useParams();
  const data = getDataById(eventId)
  console.log(data)
  return <div>EventPageDetail</div>;
}

And this is my server action

data-query/appointment.ts


'use server'

export async function getDataById(id: string){
  try {
    const data = await db.appoinmentSchedule.findUnique({
      where: {
        id:id
      }
    })

    return data
  } catch (error) {
    return error
  }
}

Difference between ES6 Tagged template literals and Input?

In mssql,

ES6 Tagged template literals uses this syntax:

return sql.query`select * from mytable where id = ${value}`

Input uses this syntax:

request.input('input_parameter', sql.Int, value)

In terms of benefit, there is a one thing that I see using Input over Tagged template literals. It is the data type specification. However, both can prevent SQL injection from what I understand.

My question is what are the other differences between ES6 Tagged template literals and Input if any? because if there is none then I think using input is just better. I’m in a process to decide which one to use as a standard way of coding this.

_a.Socket is not a constructor

I have an electron app that should do with the TCP server and on my client side I had this error”_a.Socket is not a constructor”, after connecting to my server, the server worked normally, but the connection had issues, connection code below

var client = new net.Socket();
    client.connect(3000, '127.0.0.1', function() {
    console.log('Connected');
    client.write('Hello, server! Love, Client.');
});

How to catch error in XMLHttpRequest call with caller function

I am building a feature in ReactJS that allows a user to upload files to a photos app. My backend validates the files to ensure they are of a supported type, and not some random type like .txt or .bat or some other non-image file type. If the user attempts to upload an unsupported type, the server responds with an HTTP 415 error “Unsupported Media Type.” I’m able to access this status code in the function that sent this request, shown below:

export function sendCSRFRequest(formData, targetURL) {  
    const request = new XMLHttpRequest();

    // check for HTTP response status
    request.onreadystatechange = () => {
        if (request.readyState === 4) {
            if (request.status === 200) {
                console.log("Upload successful!");
            } else if (request.status === 415) {
                throw new Error("Can't upload that!");
            }
        }
    };

    request.open('POST', targetURL);
    request.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
    request.send(formData);
};

This code successfully identifies the 415 error and throws the error to the console with text, “Can’t upload that!” But what I want to do is hand this error back to the calling function so I can do some conditional rendering and show the user an alert that tells them what went wrong directly in the UI. Here is the calling function:

async function handleUpload(e, files, setFiles, setUploadFailed) {
    e.preventDefault() // do not redirect page
    const formData = new FormData();
    files.forEach(file => {formData.append('file', file)});
    try {
        sendCSRFRequest(formData, 'api/upload/'); // Function shown above
    } catch (e) {
        console.log("Found an error!");
        console.error(e);
        setUploadFailed(true); // Triggers an alert in the UI
    }
    
    await setFiles([]); // If upload is successful, clear out state "files"
};

This second function doesn’t seem to be catching the error I am throwing in the first function, and I can’t understand why. I’ve tried setting up my try/catch block in various ways, adding and removing “await” on various lines, changing to sendCSRFRequest().catch(e => /* do something */), nothing I try seems to work. Does the error thrown in the sendCSRFRequest function not bubble all the way back up to the calling function for some reason? Do I need to do something different when throwing the error so that it will bubble back up to the caller? Am I not properly catching the error as it bubbles back up?

TypeError: setAuth is not a function (React Authentication with JWTs)

I have been banging my head against the wall trying to figure this out. It should be so simple and yet I can’t figure out what’s wrong.

const useRefreshToken = () => {
  const { setAuth } = useAuth();

  const refresh = async () => {
    try {
      const response = await axios.get('/refresh', {
        withCredentials: true,
      });

      console.log(response.data);

      setAuth(response.data); // ! Problem

      return response.data;
    } catch (err) {
      console.error(err);
    }
  };
  return refresh;
};

My refresh function should be using the user’s refresh token to generate a new accessToken, then it will save that accessToken to my auth state with setAuth.

I use setAuth and auth in multiple components in my code base and it works just fine. But now however I am getting

TypeError: setAuth is not a function

My hope was that setAuth would simply add the accessToken to the auth state and that would be it.

setAuth takes an object which is what response.data is returning.

I have tried multiple different ways of using setAuth, and I am unsure what to focus on next.