Installing npm packages listing many errors using nodejs

I am working on Windows, using NodeJS method, firstly, I found difficulty in making node_modules folder even after writing “npm install” command. Secondly, there is a list of errors if I install any of the npm packages. Similarly, I installed express through command “npm install express” and this is what I got.

npm WARN tar TAR_ENTRY_ERROR UNKNOWN: unknown error, write
npm WARN tar TAR_ENTRY_ERROR EBADF: bad file descriptor, write
npm WARN tar TAR_ENTRY_ERROR UNKNOWN: unknown error, write
npm WARN tar TAR_ENTRY_ERROR EBADF: bad file descriptor, write
npm ERR! code EBADF
npm ERR! syscall write
npm ERR! errno -4083
npm ERR! EBADF: bad file descriptor, write

Kindly assist me in resolving these issues!

how to take value resultgood from the ajax table ,cause value can’t put to resultgood

i have case can’t take value from resultgood from ajax table in table ajax from database

{
            targets: 2,
        orderable: false,
        render: function(data, type, row) {        

            var resultGood = 'kosong';
                
                $.ajax({
                    type: "GET",
                    url:  hostBaseUrl+"admin/fetch-datakelas",
                    dataType: "json",
                    success: function (response) {                                             
                                $.each(response.data_kelas, function (key, item) {
                                    if (row.id == item.ppdb_id) {                                    
                                        alert(item.nisn);
                                       resultGood = item.nisn;
                                    }                               
                                });  
                        }
                    });                        
            return resultGood;
            }
        },

how to take value resultgood from the ajax table ,cause value can’t put to resultgood…

Passing parameters to a previous screen in react native

I have 2 Screens im trying to pass parameters between. HomeScreen is the previous screen in this case.

function HomeScreen(props: {
  //some props
  route:any, 
  navigation:any,
}) {
   React.useEffect(() => {
     if (props.route.params?.defined) {
       console.log(props.route.params?.defined);
     }
   }, ); //rest of the code

Second component

function SavedRoutesScreen(props: { navigation: any }) {
  function handleGo() {
   props.navigation.navigate({
     name: "Home",
     params: { defined: true },
   });
  } //rest of the code

Basically im trying to pass parameters from SavedRoutesScreen to HomeScreen but I get this error. : “TypeError: undefined is not an object (evaluating ‘props.route.params’)”
anyone know whats up with this?

Apex Charts Custom tooltip: How to alter alignment of seriesName or delete seriesName?

I am trying to get the series name aligned to center beside the color in the tooltip, as the value in my tooltip has a couple of lines of data. How do I align it to center beside the color? or may we delete the series name from the tooltip if we cannot align?
Please view the attached image for a clear understanding of my question.

    series: [
      { name: 'Low (0 - 25%)', data: [rep_estval_low[1], 200000, 1000000, 500000, 400000, 600000], labels: rep_label_low.slice(1, 7) },
      { name: 'Medium (50%)', data: [600000, 120000, 650000, 750000, 110000, 900000], labels: rep_label_med.slice(1, 7) },
      { name: 'High (75 - 100%)', data: [rep_estval_high[1], 900000, 115000, 350000, 650000, 120000], labels: rep_label_high.slice(1, 7) }
    ],
    
    tooltip: {
         y: {
        formatter: function (value, { seriesIndex, dataPointIndex, w }) {
          var label = w.config.series[seriesIndex].labels[dataPointIndex];
          var labelTooltip = label.replace(/n/g, '<br>');
          return labelTooltip;
        }
      }
      
    },
    xaxis: {
    categories: ['<0 Days', '0-30 Days', '31-60 Days', '61-90 Days', '91-180 Days', '>180 Days'],
    labels: { show: true }},

Tooltip image

Append an object instead of an element to a div

I have this joinRoomInit function :

let joinRoomInit = async () => {
  // ...
  joinStream();
  client.on("user-published", handleUserPublished);
};

It executes joinStream then wait for the user-published event to execute handleUserPublished.

joinStream and handleUserPublished are doing almost the same task:

let joinStream = async () => {

  // create  new video__container div dynamically
  var playerDiv = document.createElement("div"); // create div 1
  playerDiv.className = "video__container"; // add class
  playerDiv.id = `user-container-${uid}`; // add id
  var videoPlayerDiv = document.createElement("div"); // create div 2
  videoPlayerDiv.className = "video-player"; // add class
  videoPlayerDiv.id = `user-${uid}`; // add id
  playerDiv.appendChild(videoPlayerDiv); // append div 2 to div 1

  // append it to streams__container
  document
    .getElementById("streams__container")
    .insertAdjacentElement("beforeend", playerDiv);

  // play the video  on the div with user-${uid} ID
  localTracks[1].play(`user-${uid}`);
  // publishing (trigger user-publish event)
  await client.publish([localTracks[0], localTracks[1]]);
};


let handleUserPublished2 = async (user) => {

  console.log("user: ", user);

  // create  new video__container div dynamically
  var playerDivRemote = document.createElement("div");
  playerDivRemote.className = "video__container";
  playerDivRemote.id = `user-container-${user.uid}`;
  var videoPlayerDivRemote = document.createElement("div");
  videoPlayerDivRemote.className = "video-player";
  videoPlayerDivRemote.id = `user-${user.uid}`;
  playerDivRemote.appendChild(videoPlayerDivRemote);

  console.log("playerDivRemote: ", playerDivRemote);

  document
    .getElementById("streams__container")
    .insertAdjacentHTML("beforeend", playerDivRemote);

  // play the video  on the div with user-${uid} ID
  user.videoTrack.play(`user-${user.uid}`);
};

joinStream works fine, it creates a div and appends it to streams__container, However, handleUserPublished appends a "[object HtmlDivElement]" to the DOM even when the div is properly created, I can see it in the console.

I wonder what’s the reason behind this, couldn’t find out the difference.

Cannot return privatePasswordLeakVerification property from Google reCaptcha Enterprise Assessment

I am trying to get the privatePasswordLeakVerification property back from a reCaptcha Enterprise assessment using the RecaptchaEnterpriseServiceClient. I have billing enabled. I am using the Node.js example found at link below although I am not using TypeScript:

https://cloud.google.com/recaptcha-enterprise/docs/check-passwords#recaptcha_enterprise_password_leak_verification-typescript

Here is an example of the code I am using to make the request:

const {RecaptchaEnterpriseServiceClient} = require("@google-cloud/recaptcha-enterprise");

const {PasswordCheckVerification} = require('recaptcha-password-check-helpers');

const client = new RecaptchaEnterpriseServiceClient({
  credentials: JSON_FILE
});

async function checkPasswordLeak(
  projectId,
  username,
  password,
  token
) {

  const verification = await PasswordCheckVerification.create(username, password);

  const lookupHashPrefix = Buffer.from(
    verification.getLookupHashPrefix()
  ).toString('base64');

  const encryptedUserCredentialsHash = Buffer.from(
    verification.getEncryptedUserCredentialsHash()
  ).toString('base64');

  const createAssessmentRequest = {
    parent: `projects/${projectId}`,
    assessment: {
      privatePasswordLeakVerification: {
        lookupHashPrefix,
        encryptedUserCredentialsHash,
      },
      event: {
        token,
        siteKey
      }
    },
  };

  const [response] = await client.createAssessment(createAssessmentRequest);

  return response;

}

Here is the response I get back:

{
  name: 'projects/111111111111/assessments/111111111111111',
  event: {
    token: '...',
    siteKey: '...',
    userAgent: '',
    userIpAddress: '',
    expectedAction: '',
    hashedAccountId: { type: 'Buffer', data: [] }
  },
  riskAnalysis: { reasons: [], score: 0.8999999761581421 },
  tokenProperties: {
    valid: true,
    invalidReason: 'INVALID_REASON_UNSPECIFIED',
    createTime: { seconds: '1685499273', nanos: 677000000 },
    hostname: 'localhost',
    action: 'LOGIN'
  },
  accountDefenderAssessment: null
}

As you can see I have no privatePasswordLeakVerification property in the reponse object.

Module not found: Can’t resolve ‘./Header’ in ‘D:React-TaigataigasrcstoriesHeader’ src/stories/Header/Header.stories.tsx

What I alway get this error , seem my directory is correct.
This is my directoryenter image description here

Here is my Header.stories.tsx code

import React from "react";
import { Meta, Story } from "@storybook/react";

import Header from "./Header";

export default {
  title: "stories/Header",
  component: Header,
} as Meta;

const Template: Story = (args) => <Header label={""} {...args} />;

export const HeaderStory = Template.bind({});
HeaderStory.storyName = "Top Header";
HeaderStory.args = {};

Here my Header.tsx code

import React, { memo } from "react";
import "./header.css";

interface HeaderOptions {
  label: string;
}

const Header = ({ label, ...props }: HeaderOptions) => (
  <>
    <div>Hi</div>
  </>
);

export default memo(Header);

Is it possible to build a custom webhooks on top of an existing web page?

What I want to do is create a custom layer (which I’m not sure if I should call middleware) that allows me to perform additional functionality through network communication on top of an existing web page.

Currently, I am using Puppeteer to run the web page and using the Page.on method to execute my custom functions whenever a request occurs.

Example

javascript

  const browser = await puppeteer.launch({headless: false, defaultViewport: null });
  const page = await browser.newPage();

  await page.goto('http://example.com');

...

  page.on('request', (req) => {
    const request = {
      header: req.headers(),
      initiator: req.initiator(),
      method: req.method(),
      postData: parseJSON(req.postData()),
      url: req.url()
    }
    if(request.method === "POST" && request.postData["message"]) {
      customFunction()
    }
  });

While this approach works as I envisioned, but I want to build another web page or a desktop app whice I can apply custom callback functions through network communication on an existing web page. I apologize if my explanation is not clear enough.

Any suggestions would be highly appreciated !!

Failed to resolve module ‘C:Users***DesktopBotmodulesdataMongoDB.js’: ExpectedValidationError > s.instance(V)

I’m attempting to setup a MongoDB connection, but I’m running into an error when launching my bot.

Failed to resolve module 'C:UsersluciDesktopLunar BotmodulesdataMongoDB.js': ExpectedValidationError > s.instance(V)

Bot is being developed in typescript and is being converted into JS on load.

import mongoose from "mongoose";

export class MongoConnection {
  public versions = "^7";
  public mongoose!: typeof mongoose;

  async onstart() {
    this.mongoose = await mongoose.connect(process.env.MONGODB!);

    if (this.mongoose) console.log("Connected to MongoDB Database");

    return true;
  }
}

export default new MongoConnection();

Converted JS Code

import mongoose from "mongoose";
export class MongoConnection {
    constructor() {
        this.versions = "^7";
    }
    async onstart() {
        this.mongoose = await mongoose.connect(process.env.MONGODB);
        if (this.mongoose)
            console.log("Connected to MongoDB Database");
        return true;
    }
}
export default new MongoConnection();
//# sourceMappingURL=MongoDB.js.map

Any idea as to why I’m having an error occur?

How to upload an image with sequelize to mysql?

I want to upload an image into a table of mysql, using express and its dependence multer. I’m new, I donĀ“t know if I just need to send the name of the image, example: image-111111-12312.jpg? So where does the file is gonna be saved if just an string is uploaded?

I have creatde the form and all the code of multer. It is working and I can save the name of the image locally in a JSON. I have also created the model and its conection to my DB. What datatype do I need to chose for the image? dataTypes.STRING?

My controller, looks like:

createStore: (req,res) => {
  const newProduct = { 
  id: products[products.length - 1].id + 1, 
  ...req.body,  
  image: req.file.filename //We add the name of the image what is shared thanks to multer
  }
  products.push(newProduct)
  fs.writeFileSync(productsFilePath, JSON.stringify(products, null, ' ')) 
  res.redirect("/products")
}

how to get items object from array and use it in another function?

i would like to ask a solution for my react project component

const handleGenerateBarcode = (e, item, detailID, qty) => {
e.preventDefault();
let details = transformationDetails;

const transformationDetailID = item?.transformationDetailBarcode.filter((obj) =>obj.transformationDetailId === item.id)

console.log(“transformationDetailID”, transformationDetailID)

const transformationDetail = transformationDetails.filter((detail) => detail.id === item.id);
console.log(“transformationDetail”, transformationDetail)

setBarcode(transformationDetailID);
setShowModal(true);
};

const renderBarcodeModal = () => {
return (

<div className=”modal-header d-flex justify-content-center align-items-center” style={{ backgroundColor: “#3A936C”, color: “white” }}>

Barcode

{barcode.map((item, index) => {
return (

<div className=”d-flex justify-content-center align-items-center flex-column” style={{ color: “black”, marginBottom: ’20px’ }}>
<img src={https://chart.googleapis.com/chart?cht=qr&chl=${${item.itemId}-${index}}&chs=250x250} id=”barcode” alt=”Barcode” style={{ width: “100%” }} />

{workOrderNo}/{items?.code}/{item.itemId}/({index + 1})

);
})}

<div className=”btn btn-secondary mt-2″ data-dismiss=”modal” style={{ backgroundColor: “white”, color: “#498B71″ }} id=”close_modal”>
Close

<div className=”btn btn-primary mt-2″ style={{ marginLeft: ’40px’ }} onClick={handleDownloadQR}>
Download

<div className=”d-flex flex-row” style={{ marginLeft: ’30px’ }}>
{reactToPrintTrigger()}

);
};

how do i map transformationDetails array in my handleGenerateBarcode to get the code params from the items object inside the array then how do i use it into my renderBarcodeModal function for the {items.code} label

How to set a button on Vue to appear once all API calls have finished retrieving data?

How can I set my report button to appear once all the data is loaded from the most recent click of my budget button? I have a button once clicked gets budgets and displays them on a grid in Vue using a Kendo Grid. To load the data faster it will load the grid with the initial data before calling another API to get two more columns of data for the grid. These second round of calls can take a while so they are set to go 10 at a time in a for loop. What is the easiest way to display this button once the data is done loading?

I posted my current method to get my budgets and the computed I am setting the report button to appear when true. Some current issues I am facing are with multiple clicks to the get budgets button, even if I set the estimateAmounts object array to empty at the beginning of the getBudgets method, the loop from the previous call may still be iterating and could still add to the estimateAmounts offsetting it from being able to == the data object in my computing. Any ideas or direction on the best way to go with this one? Please let me know if you have any questions or need any more information.

    data() {
                return {
                    budgets: [],
                    estimateAmounts: {},
                }
           },
methods: {
    async getBudgets() {

                this.isLoading = true;
                this.budgets = []
                this.estimateAmounts = {}
                const data = await api.budget.getBudgetReport({ 
                  accountIds: this.accountIds.map(a => a.accountId),
                  salesRepIds: this.selectedSalesReps.map(sr => sr.userId),
                  startDate: this.startDate, 
                  endDate: this.endDate 
                })
                this.budgets = data.map(d => { return { ...d, startDate: new Date(d.startDate) } })
                this.isLoading = false;

                // group calculations in 10's to run concurrently and return results faster
                let idSets = chunk(data.map(d => d.budgetId), 10)
                for (const ids of idSets)
                    api.budget.calculateTotalsForBudgets(ids, this.user.userId)
                        .then(res => this.estimateAmounts = { ...this.estimateAmounts, ...res })
            },
    },

    computed: {
        setButtons() {
                        return Object.keys(this.estimateAmounts).length == this.budgets.length && this.budgets.length > 0
                    },
    }

Is there any method that I can use to properly implement the delete and edit logic in this code and alternative for select to choose multiple roles?

  • I could not delete and edit properly this code. I always got an error when I want to delete and edit the newest user I created.

  • I couldn’t set multiple roles, I have tried React Select but i could not configure it properly. I have tried so many methods but it did not work out properly. I think it has something to do with axios or the id in the elements.

import { useState, useEffect } from "react";
import { FiArrowLeft } from "react-icons/fi";
import { BsFillPersonPlusFill, BsThreeDotsVertical } from "react-icons/bs";
import { MdOutlineEmail } from "react-icons/md";
//import { useSelector, useDispatch } from "react-redux";
//import { useNavigate } from "react-router-dom";
//import {
  register,
  reset,
} from "../../features/authentication/authenticationSlice";
import "./Admin.css";
import axios from "axios";
import FormInputs from "./FormInputs";
import AdminSidebar from "./AdminSideBar";

const Admin = () => {
  const [showModal, setShowModal] = useState(false);
  const [message, setMessage] = useState("");
  const [showEditModal, setShowEditModal] = useState(false);
  const [showDeleteModal, setShowDeleteModal] = useState(false);
  const [adminItems, setAdminItems] = useState([]);
  const [roles, setRoles] = useState("");
  const [name, setName] = useState("");
  const [email, setEmail] = useState("");
  const [pic, setPic] = useState(null);
  const [password, setPassword] = useState("");
  const [password2, setPassword2] = useState("");
  const [editIndex, setEditIndex] = useState(null); // Added new state for tracking the index of the item being edited
  const [showModal2, setShowModal2] = useState(
    Array(adminItems.length).fill(false)
  );
  const [deleteIndex, setDeleteIndex] = useState(null);

  useEffect(() => {
    setShowModal2(Array(adminItems.length).fill(false));
  }, [adminItems]);

  const toggleModal2 = (index) => {
    setShowModal2((prevShowModal2) => {
      const newShowModal2 = [...prevShowModal2];
      newShowModal2[index] = !newShowModal2[index];
      return newShowModal2;
    });
  };

  const onChange = (e) => {
    const { name, value } = e.target;
    if (name === "roles") {
      const selectedOptions = Array.from(
        e.target.selectedOptions,
        (option) => option.value
      );
      setRoles(selectedOptions); // Store the array of selected roles directly
    } else if (name === "name") {
      setName(value);
    } else if (name === "email") {
      setEmail(value);
    } else if (name === "password") {
      setPassword(value);
    } else if (name === "password2") {
      setPassword2(value);
    }
  };

  const handleFileChange = (e) => {
    const file = e.target.files[0];
    setPic(file);
  };

  const handlePasswordConfirm = () => {
    if (password !== password2) {
      alert("Passwords do not match");
    }
  };

  const handleAddItem = () => {
    if (!roles || !name || !email || !password || !password2) {
      alert("Please fill in all the required fields");
      return;
    }

    const newUser = {
      roles,
      name,
      email,
      pic,
      password,
    };

    axios
      .post("/api/admins", newUser)
      .then((response) => {
        setAdminItems((prevItems) => [...prevItems, response.data]);
        setRoles("");
        setName("");
        setEmail("");
        setPic(null);
        setPassword("");
        setPassword2("");
        setShowModal(false);
      })
      .catch((error) => {
        console.log("Error adding user:", error);
      });
  };

  const handleEditItem = () => {
    if (editIndex === null) {
      alert("User not found");
      return;
    }

    const admin = adminItems[editIndex]; // Retrieve the admin being edited
    const adminId = admin.id; // Get the ID from the admin object

    const updatedUser = {
      roles: roles, // Update the roles assignment to use the roles state directly
      name,
      email,
      pic,
      password,
    };

    axios
      .put(`/api/admins/${adminId}`, updatedUser)
      .then((response) => {
        const updatedItems = [...adminItems];
        updatedItems[editIndex] = response.data;
        setAdminItems(updatedItems);
        setShowEditModal(false);
        setEditIndex(null);
      })
      .catch((error) => {
        alert("Error editing user:", error);
      });
  };

  const handleDeleteItem = (id) => {
    if (window.confirm("Are you sure you want to delete this user?")) {
      axios
        .delete(`/api/admins/${id}`)
        .then((res) => {
          setMessage(res.data.message);
          setShowDeleteModal(true);

          // Update the adminItems state after successful deletion
          setAdminItems((prevItems) =>
            prevItems.filter((item) => item.id !== id)
          );
        })
        .catch((error) => {
          alert("Error deleting user:", error);
        });
    }
  };

  useEffect(() => {
    axios
      .get("/api/admins")
      .then((response) => {
        const admins = response.data.map((admin) => ({
          ...admin,
          id: admin._id, // Add the id field to each admin object
        }));
        setAdminItems(admins);
      })
      .catch((error) => {
        console.log("Error fetching admin items:", error);
      });
  }, []);

  const handleEditClick = (index) => {
    const admin = adminItems[index];
    setRoles(admin.roles);
    setName(admin.name);
    setEmail(admin.email);
    setPassword(""); // Clear the password field when opening the edit modal
    setPassword2(""); // Clear the password2 field when opening the edit modal
    setEditIndex(index); // Set the editIndex state with the correct index
    setShowEditModal(true);
  };
  const handleAddClick = () => {
    setRoles("");
    setName("");
    setEmail("");
    setPassword(""); // Clear the password field when opening the edit modal
    setPassword2(""); // Clear the password2 field when opening the edit modal

    setShowModal(true);
  };

  return (
    <>
      <AdminSidebar />
      <div className="all">
        <div className="container-admin">
          <section className="section-admin">
            <div className="side-line" />
            <div className="side-lines" />
            <div className="admin-controller">ADMIN CONTROLLER</div>
          </section>
          <section className="section-back">
            <FiArrowLeft />
            <div className="back">BACK</div>
          </section>
        </div>
        <div className="main-section">
          <section className="sub-section-1">
            <div className="user-container">
              <div className="User">User</div>
              <div className="admin-per-department">Admin per department</div>
            </div>
            <div className="class-buttons">
              <button
                className="add-user-button-container"
                onClick={handleAddClick}>
                <BsFillPersonPlusFill />
                <div className="new-role">New Role</div>
              </button>
            </div>
          </section>
          {showModal && (
            <div className="modal-overlay">
              <div className="modal-content">
                <h3>Add New User</h3>
                <div>
                  <div className="permission">
                    by adding a new user you are giving them permission to make
                    changes in this department.
                  </div>
                </div>

                <FormInputs
                  roles={roles}
                  name={name}
                  email={email}
                  password={password}
                  password2={password2}
                  onChange={onChange}
                  handleFileChange={handleFileChange}
                  handlePasswordConfirm={handlePasswordConfirm}
                />

                <button onClick={handleAddItem}>Add</button>
                <button onClick={() => setShowModal(false)}>Cancel</button>
              </div>
            </div>
          )}

          <section className="sub-section-2">
            {adminItems.map((item, index) => (
              <div className="user-sub-section" key={index}>
                <div className="triple-dot">
                  <div className="dot">
                    <BsThreeDotsVertical
                      onClick={() => {
                        toggleModal2(index); // Toggle showModal2 for the clicked user item
                      }}
                    />
                    {showModal2[index] && (
                      <div className="dot-menu">
                        <button
                          onClick={() => {
                            handleEditClick(index); // Pass the index to handle the edit click
                            toggleModal2(index);
                          }}>
                          Edit
                        </button>
                        <button
                          onClick={() => {
                            handleDeleteItem(item.id); // Pass the item's id instead of index
                            toggleModal2(index);
                          }}>
                          Delete
                        </button>
                      </div>
                    )}
                  </div>
                </div>
                <div className="profile-container">
                  <img
                    alt="User Profile"
                    className="User-Profile"
                    src={
                      item.pic && item.pic.data
                        ? URL.createObjectURL(
                            new Blob([item.pic.data], {
                              type: item.pic.contentType,
                            })
                          )
                        : "https://icon-library.com/images/anonymous-avatar-icon/anonymous-avatar-icon-25.jpg"
                    }
                  />
                  <div className="active-status" />
                </div>
                <div className="employee-name">{item.name}</div>
                <div className="admin-container">
                  <div className="admin-at">Admin at</div>
                  <div className="department-name">
                    {item.roles || "No Role"}
                  </div>
                </div>
                <div className="email-section">
                  <div className="email-container">
                    <MdOutlineEmail />
                  </div>
                  <div className="employee-email">{item.email}</div>
                </div>
              </div>
            ))}
          </section>
          {/* Edit Modal */}
          {showEditModal && (
            <div className="modal-overlay">
              <div className="modal-content">
                {/* Modal content for editing user */}
                <h3>Edit User</h3>

                <FormInputs
                  roles={roles}
                  name={name}
                  email={email}
                  password={password}
                  password2={password2}
                  onChange={onChange}
                  handleFileChange={handleFileChange}
                  handlePasswordConfirm={handlePasswordConfirm}
                />
                <button
                  onClick={() => {
                    handleEditItem();
                  }}>
                  Save
                </button>
                <button onClick={() => setShowEditModal(false)}>Cancel</button>
              </div>
            </div>
          )}
        </div>
      </div>
    </>
  );
};

export default Admin;

PHP strtotime value convert to Date time using javascript

So I am using an api that has a field createdAt and was filled using strtotime function of PHP. Since I am using the API and I am using javascript I need to convert the value to be a date time format using javascript.

Is there a way to do this?

I tried the following

const a = 1440629186;
var dateFormat = new Date(a);
console.log(dateFormat)

The above code always logs Sun Jan 18 1970 00:10:29 GMT+0800 (Philippine Standard Time)