esbuild Include folder/file to the bundle

I am developing lambda function with serverless framework, that uses esbuild under the hood. This function is going to send emails, so i need to store templates along with ts code. The problem is that i need to take the folder with templates to the builded bundle, and i cannot find a esbuild configuration to do that.

I have tried a different esbuild options: --externals – no profit, --add-externals – didnt find a way to specify it in esbuild config in serverless.yml. GPT suggested a custom plugin implementation, but i hope there is a simple way of adding external folders to the bundle.

Why isnt my service-worker.js able to cache files these two files?

I cant seem to be able to cache these two files that are essential to the functionality of my PWA

Below is my app file structure:

apps.js
package.json
package-lock.json
.env
README.md

|--public
|--|
|--css
|--javascripts
|--images
|--modules
|--manifest.json
|--service-worker.js
|--views
|--|
|--driversLogin.ejs
|--driverLoggedIn.ejs

Following is the section of my service-worker.js file that seems to cause the error message: Uncaught (in promise) TypeError: Failed to execute 'add' on 'Cache': Request failed

const cacheName = 'scan-and-save-cache_V004';
const filesToCache = [
    '/',
    '../views/driversLogin.ejs',
    // '../views/driverLoggedIn.ejs',
    '/css/bootstrap.min.css',
    '/css/styles.css',
    '/images/favicon.ico',
    '/images/scan&SaveHearderIcon.png',
    '/images/scan&SaveLogoSmall.png',
    '/javascripts/jquery-3.4.1.js',
    '/javascripts/popper.min.js',
    '/javascripts/bootstrap.min.js',
    '/javascripts/main.js',
    '/javascripts/app.js',
];

It seems like the service-worker.js isnt able to cache the two files: ../views/driversLogin.ejs, ../views/driverLoggedIn.ejs. When I comment them out as seen below the error message disappears and I am able to run my PWA perfectly.

const cacheName = 'scan-and-save-cache_V004';
const filesToCache = [
    '/',
    // '../views/driversLogin.ejs',
    // '../views/driverLoggedIn.ejs',
    '/css/bootstrap.min.css',
    '/css/styles.css',
    '/images/favicon.ico',
    '/images/scan&SaveHearderIcon.png',
    '/images/scan&SaveLogoSmall.png',
    '/javascripts/jquery-3.4.1.js',
    '/javascripts/popper.min.js',
    '/javascripts/bootstrap.min.js',
    '/javascripts/main.js',
    '/javascripts/app.js',
];

It is essential for me that these two files be cached, can you guide me on how to cache them?

WebSocket connection fails when deploying Spring web application to a server on my domain

I’m encountering an issue with WebSocket connectivity in my Spring web application. Locally, when I run the application, WebSocket connections are established successfully. However, upon deploying the application to a server on my domain, WebSocket connections fail to establish. The browser console displays the following error:

WebSocket connection to 'wss://merkeido.com/ws/776/1lq4jnfq/websocket' failed:

Additional Information:

  • The application works fine locally, but encounters issues on deployment to a server.
  • The server returns a 403 (Forbidden) status code.
  • The WebSocket endpoint is wss://merkeido.com/ws/776/1lq4jnfq/websocket.

What I’ve Tried:

  1. Ensuring WebSocket support is enabled in the Spring configuration.
  2. Verifying WebSocket endpoint URLs and configurations.
  3. Checking server logs for any relevant error messages.

Question:
What could be causing the WebSocket connection to fail on deployment, specifically resulting in a 403 (Forbidden) error? Any insights or suggestions for troubleshooting would be greatly appreciated. Thank you!

WebSocket Configuration:
Here is my WebSocket configuration class:

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

    @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
        config.enableSimpleBroker("/user");
        config.setApplicationDestinationPrefixes("/app");
        config.setUserDestinationPrefix("/user");
    }

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/ws").withSockJS();
    }
}

HTML/JavaScript:
And here is my HTML/JavaScript code for establishing WebSocket connections:

<script src="https://cdnjs.cloudflare.com/ajax/libs/sockjs-client/1.1.4/sockjs.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/stomp.js/2.3.3/stomp.min.js"></script>

<script th:inline="javascript"> 
    'use strict'; 
    
    let stompClient = null;
    let selectedUserId = null;
    let userId = user_id;
    
    connect();
    function connect() {
        const socket = new SockJS('/ws');
        stompClient = Stomp.over(socket);
    
        stompClient.connect({}, onConnected, onError);
    }
    
    function onConnected() {
        stompClient.subscribe(`/user/${userId+""}/queue/messages`, onMessageReceived);
        stompClient.subscribe(`/user/public`, onMessageReceived);
    
        // Register the connected user
        stompClient.send("/app/user.addUser",
            {},
            JSON.stringify({id: userId+"", c_status: 'ONLINE'})
        );
        
        findAndDisplayConnectedUsers().then();
    }
</script>

The actual error on my console:

Opening Web Socket...
websocket.js:6 WebSocket connection to 'wss://merkeido.com/ws/776/1lq4jnfq/websocket' failed: 
e.exports @ websocket.js:6
/ws/776/in3mqa1z/xhr_streaming?t=1714645083452:1 
        
        
       Failed to load resource: the server responded with a status of 403 ()
stomp.min.js:8 Web Socket Opened...
stomp.min.js:8 >>> CONNECT
accept-version:1.1,1.0
heart-beat:10000,10000

Input loses focus when Popover opens in ShadCN

This component contains Popover & Input from shadcn. The issue I’m facing is that when I click on the Input to open the Popover, the Input loses focus, and the cursor moves out.

Expected behavior:
When clicking on the Input component, the Popover should open, and the Input should remain focused with the cursor inside it, allowing the user to type without any additional clicks.

Link to Sandbox

"use client";

import { Input } from "@/components/ui/input";
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from "@/components/ui/popover";

export default function Searchbar() {
  return (
    <div className="w-1/3">
      <Popover>
        <PopoverTrigger>
          <Input />
        </PopoverTrigger>
        <PopoverContent>Place content for the popover here.</PopoverContent>
      </Popover>
    </div>
  );
}

In Observable/d3/javascript, how do you apply a filter from based on a action in one plot to another plot?

I have 2 functions in Observable which each create a plot. I designed it so that when I click the squares in the legend of the first plot, it filters which data is displayed (there are 7 lines for each. of 7 object_types). That works! But I want to also filter the second plot based on the selections made in that first plot. The 2 functions use different datasets for their plots.

I combine the 2 functions with this code:

{
 
  const { svg , selectedObjectsMap } = objects_over_time()
  const vis_right = plot_objects(selectedObjectsMap);

  return html`<div style="display: flex">${svg}${vis_right}</div>`;
} 

The first function returns an svg element and a map which maps each of 7 object_types to either true or false.

The plot_objects() function is called with this true/false map as an argument whenever a square is clicked in the first plot.

  function onclick(event, d) {
    const selectedObjectType = d3.select(event.target).datum();
    const isSelected = selected.get(selectedObjectType);
    const square = d3.select(this);
    square.attr('fill', isSelected ? 'white' : color(selectedObjectType));
    selected.set(selectedObjectType, !isSelected);
    
    const filteredData = new Map();
    objects_grouped.forEach((group, object_type) => {

        const includeObject = selected.get(object_type);
        const filteredGroup = includeObject ? group.filter(obj => obj.location === selectedLocation) : [];
      
        filteredData.set(object_type, filteredGroup);
    });

    svg.selectAll('#plot-line').remove();
    drawLines(filteredData);
    plot_objects(selected);
  }

The plot_objects() function has a function updateVisualization() which draws new datapoints based on the filtering. This works for the location filter which is done in a separate drop-down menu. I’ve printed console.log statements and I can see it has the right data and filters it properly, but it just doesn’t update the data points.

  function updateVisualization(location) {

    svg.selectAll('#data-points').remove()
    const filteredData = all_data.filter(d => d.location === location &&
                                         selectedObjects.has(d.object_type) &&
                                         selectedObjects.get(d.object_type));
    console.log("plot_objects:", filteredData)
    drawPoints(filteredData)
    updateBackground(location)
  }

  updateVisualization(selectedLocation)

  function drawPoints(data) {
    console.log("in drawPoints function:", data)
    svg.selectAll('rect:not(#tooltip-rect):not(#image)')
      .data(data)
      .join('rect')
        .attr('id', 'data-points')
        .attr('x', d => x_rv(d.x))
        .attr('y', d => y_rv(d.y))
        .attr('fill', d =>  color(d.object_type))
        .attr('opacity', 0.5)
        .attr('width', d => sizeScaleW(d.object_type))
        .attr('height', d => sizeScaleH(d.object_type))
        .on('mouseenter', handleMouseEnter)
        .on('mouseleave', handleMouseLeave)
        .raise();
  }

Changing svg.selectAll('#data-points').remove() to d3.selectAll('#data-points').remove() in the updateVisualization function did finally remove all of the data points, but none are added back in. So it seems like all of the functions are being called as expected, but I must be missing a step to make the changes actually show up in the plot.

Getting data- values from links on page to JS

I currently have a table on my page generated by PHP from a MySqli DB, which contain a name and x and y coordinates. however this means displaying the x,y and ID data on the page. I use JS to rerad the x and y in the onclick listener, I need to modify my code so that I do not need to show this info to the user. my current code is below.

<script language="javascript">
$(document).ready(function () {
  $(".systemname").on("click", function (event) {
    event.preventDefault();
    var $row = $(this).parent().parent();
    var x = $row.children().eq(2).text() + "px";
    var y = $row.children().eq(3).text() + "px";
    var m = $row.children().eq(4).text() + ".jpg";
    var i = $row.children().eq(5).text();
    $('#mapinfo').html(m);  
    var imageUrl = m;
    $("#mapcontent").css("background-image", "url(<?=$imglnk?>)");
    $("#pointer").css({"left": x, "top": y});
    $("#systeminfo").load('getsysteminfo.php?id='+i);
    
  });
});
</script>

I now need to modify my code to be able to use the following (or if there is a better solution)

<a href='#' class='systemname' data-id="1" data-points="x350y210">system 1</a>
<a href='#' class='systemname' data-id="2" data-points="x120y410">system 2</a>

bearing in mind there can be up to 20 links on the page

I have tried googling but only results seem to be for a single link on a page and not multiple

How to parse Json received in a http response

I’m doing a simple project where i need to take the user Input from a Jsp and show it in another jsp,i did send data from the first jsp using javascript but how do i parse it again with java ? In my case using javascript i wrote those function to send data from the first jsp to the a servlet in between that i use as a fake database:

    const getDataFromDom = () =>  {
    const $memoContent = document.getElementById("message").value;
    const $memoSlotNumber = document.getElementById("slot").value;
       return data = {
       content: $memoContent,
       slotNumber: $memoSlotNumber
     }
    }


const sendDataToFakeDbServlet = async () => {
    try{
        const response = await fetch('/JspTestMemoApp/FakeDb', {
            method: "POST",
            body: JSON.stringify(getDataFromDom()),
            headers: { 'Content-Type': 'application/json' }
        })
        const result = await response.text();
        state.data = result;
        console.log(state.data);
        console.log(getDataFromDom());
    }catch(error){
        console.error(error);
    }
}

in the doPost method in the servlet i receive the data in the response like this :
{content: ‘box1’, slotNumber: ‘1’}
as a string how do i parse it and get the value of content and value of slotNumber ?

Blazor App (server rendering) -> Service for handle sizechange of DOM object

Javascript is not my strongest part and absolutely not in combination of Blazor but have with Google and some AI get an eventlistener that run code on my Blazor application if browsersize change.
Now I need to do the same with some of my <div id="abc"> because I have components that need to set height / width in pixels.

My Blazorfile :

@inject DivSizeService dServer

.. html ..


@code {
.. 
protected override async Task OnInitializedAsync()
{
    dService.OnDivSizeChanged += HandleDivSizeChanged;  
}

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {

        if (firstRender)
        {
            await dService.StartListeningForDivSizeChanges("abc");
            await UpdateDivSize();
        }
    }

    private async void HandleDivSizeChanged(object sender, DivSizeChangedEventArgs e)
    {
        if (e.ElementId == "abc")
        {
            await UpdateDivSize();
        }
    }

    async Task UpdateDivSize()
    {
        divSize = await dService.GetDivSize("abc");
        Style = "Width: " + (divSize.Width - 50).ToString() + "px; Height: " + 
            (divSize.Height - 50).ToString() + "px;";

        ChildComponent.Refresh // pseudocode
    }

And my DivSizeService :

public class DivSizeService
{
    private readonly IJSRuntime _js;

    public event EventHandler<DivSizeChangedEventArgs> OnDivSizeChanged;

    public DivSizeService(IJSRuntime js)
    {
        _js = js;
    }

    public async Task<DivSize> GetDivSize(string elementId)
    {
        return await _js.InvokeAsync<DivSize>("getElementDimensions", elementId);
        //var dimensions = await _js.InvokeAsync<DivSize>("getDimensionsA");
        //return new DivSize { Width = dimensions.Width, Height = dimensions.Height };
    }

    public async Task StartListeningForDivSizeChanges(string elementId)
    {
        await _js.InvokeVoidAsync("registerResizeListener", elementId);
    }

    [JSInvokable]
    public void HandleDivSizeChanged(string elementId, DivSize newSize)
    {
        OnDivSizeChanged?.Invoke(this, new DivSizeChangedEventArgs(elementId, newSize));
    }
}

public class DivSizeChangedEventArgs : EventArgs
{
    public string ElementId { get; }
    public DivSize NewSize { get; }

    public DivSizeChangedEventArgs(string elementId, DivSize newSize)
    {
        ElementId = elementId;
        NewSize = newSize;
    }
}

And my Javascript :

window.getElementDimensions = function (elementId) {
    const element = document.getElementById(elementId);
    return {
        width: element ? element.offsetWidth : 0,
        height: element ? element.offsetHeight : 0
    };

window.registerResizeListener = (element) => {
    const observer = new ResizeObserver(entries => {
        for (let entry of entries) {
            entry.target.dispatchEvent(new Event('resize'));
        }
    });

    observer.observe(element);
}

My window.getElementDimensions works, I try to run that when browsersize changed but my div won’t update size before that event are finished so that makes me get the previos size of my div.

When I use this code above I got :

Exception thrown: ‘Microsoft.JSInterop.JSException’ in System.Private.CoreLib.dll
Exception thrown: ‘Microsoft.JSInterop.JSException’ in System.Private.CoreLib.dll
Microsoft.AspNetCore.Components.Server.Circuits.RemoteRenderer: Warning: Unhandled exception rendering component: Failed to execute ‘observe’ on ‘ResizeObserver’: parameter 1 is not of type ‘Element’.
TypeError: Failed to execute ‘observe’ on ‘ResizeObserver’: parameter 1 is not of type ‘Element’.

I know that I get element = “abc” in my window.registerResizeElement but I guess it’s not the right way to do this? It crash on observer.observe(element);

The following modules are needed by other modules but have not been defined(color)

import { registry } from "@web/core/registry"
import { KpiCard } from "./kpi_card/kpi_card"
import { ChartRenderer } from "./chart_renderer/chart_renderer"
import { loadJS } from "@web/core/assets"
import { useService } from "@web/core/utils/hooks"
import {getColor} from "@web/views/graph/colors"
const { Component, onWillStart, useRef, onMounted, useState } = owl

export class OwlSalesDashboard extends Component {

    // top products
        async getTopProducts () {
            const data = await this.orm.readGroup("sale.report",[],['product_id', 'price_total'],['product_id'])
            console.log(data)
        
        this.state.topProducts = {
                data: {
                labels: data.map(d=>d.product_id[1]),
                datasets: [
                {
                Label: 'Total',
                data: data.map(d=>d.price_total),
                hoverOffset: 4,
                backgroundColor: data.map((_,index)=>getColor(index)),
                },
                {
                Label: 'Count',
                data: data.map(d=>d.product_id_count),
                hoverOffset: 4
                }]
                }
        }
        }

this is my code for create a dashboard module in odoo .
when i use this line import {getColor} from “@web/views/graph/colors” for color , i got this error.

The following modules are needed by other modules but have not been defined, they may not be present in the correct asset bundle:
@web/views/graph/colors
The following modules could not be loaded because they have unmet dependencies, this is a secondary error which is likely caused by one of the above problems:
@my_dashboard/components/sales_dashboard

please give me correct solution

How to return js function data in in google auth environment for use in another function

My test script is:

// Test file that aquires authorization to list file ids/names from My Drive > ocrTarget

const fs = require('fs');
const fsp = fs.promises;


const path = require('path');
const process = require('process');
const {authenticate} = require('@google-cloud/local-auth');
const {google} = require('googleapis');

// If modifying these scopes, delete token.json.
const SCOPES = ['https://www.googleapis.com/auth/drive'];
// File id of the file to download
const FILEID = '11Sejh6XG-2WzycpcC-MaEmDQJc78LCFg';


// The file token.json stores the user's access and refresh tokens, and is
// created automatically when the authorization flow completes for the first
// time.
const TOKEN_PATH = path.join(process.cwd(), 'DownloadFileToken.json');
const CREDENTIALS_PATH = 'C:\googleDriveDev\credentials.json';

/**
 * Reads previously authorized credentials from the save file.
 *
 * @return {Promise<OAuth2Client|null>}
 */
async function loadSavedCredentialsIfExist() {
    try {
        const content = await fsp.readFile(TOKEN_PATH);
        const credentials = JSON.parse(content);
        return google.auth.fromJSON(credentials);
    } catch (err) {
        return null;
    }
}

/**
 * Serializes credentials to a file compatible with GoogleAUth.fromJSON.
 *
 * @param {OAuth2Client} client
 * @return {Promise<void>}
 */
async function saveCredentials(client) {
    const content = await fsp.readFile(CREDENTIALS_PATH);
    const keys = JSON.parse(content);
    const key = keys.installed || keys.web;
    const payload = JSON.stringify({
        type: 'authorized_user',
        client_id: key.client_id,
        client_secret: key.client_secret,
        refresh_token: client.credentials.refresh_token,
    });
    await fsp.writeFile(TOKEN_PATH, payload);
}

/**
 * Load or request or authorization to call APIs.
 *
 */
async function authorize() {
    let client = await loadSavedCredentialsIfExist();
    if (client) {
        return client;
    }
    client = await authenticate({
        scopes: SCOPES,
        keyfilePath: CREDENTIALS_PATH,
    });
    if (client.credentials) {
        await saveCredentials(client);
    }
    return client;
}


/**
 * Lists the names and IDs of pageSize number of files (using query to define folder of files)
 * @param {google.auth.OAuth2} auth An authorized OAuth2 client.
 */
function listFiles(auth) {
  const drive = google.drive({version: 'v3', auth});
 
 
  drive.files.list({
    corpora: 'user',  
    pageSize: 100,
    // files in a parent folder that have not been trashed 
    // get ID from Drive > Folder by looking at the URL after /folders/ 
    q: `'11Sejh6XG-2WzycpcC-MaEmDQJc78LCFg' in parents and trashed=false`,    
    fields: 'nextPageToken, files(id, name)',
  }, (err, res) => {
    if (err) return console.log('The API returned an error: ' + err);
    const files = res.data.files;
    if (files.length) {
     
        var idFiles = [ ];
        files.forEach(function(file, i) {
        idFiles.push(file.id);
        idFiles.push(file.name);
        });

        // Store file id/name pairs for use later
        var fileIdentity = [];

        // Iterate over idFiles array with step of 2
        for (var i = 0; i < idFiles.length; i += 2) {
            // Push pair of values into d array
            fileIdentity.push([idFiles[i], idFiles[i + 1]]);
        }
        
        // Access pairs using indices in order to pass an array pair of file id/file name into a function
        for (var i = 0; i < fileIdentity.length; i++) {
            console.log("File id:", fileIdentity[i][0], "has file name:", fileIdentity[i][1])       
        }

    } 
    else 
        {
        console.log('No files found.');
        }

        
  });

}

authorize().then(listFiles).catch(console.error);

Output:

C:googleDriveDev>node ./exportTest3.js
File id: 15lsfdIP1Jne-x-rPI57BtWQE3W4ciZzDz9Wy4uU9J98 has file name: 31832_226133__0002-00104
File id: 1RK_172AaDBLji941voUn1TeAg6u6We-UQ8G280e2xsg has file name: 31832_226133__0002-00105
File id: 13B0Kt6PhQYalqh046eXJxnbT9ZCLZDhv2XZqF5SHdV4 has file name: 31832_226133__0002-00106
File id: 1Aj_jQ3nSZAMPlap7fC6lk2uEN7ajIuUL5Kx-JusE1O4 has file name: 31832_226133__0002-00107
File id: 1rTnen5Zhb-aV9k82cNqbbVVl8f54QDGRAdT6o7Ob2b8 has file name: 31832_226133__0002-00108

——————><—————

Instead of outputting the id/names array pairs within function listFiles() I want to return the array fileIdentity and iterate over it outside the function.

I don’t have much JavaScript experience. I find simple function returns in exercises okay. But this example has extra complications. Placing return fileIdentity has been okay (no errors) But when I try to output what’s returned my array var is determined to be undefined and trying another combination I got:

The API returned an error: Error: The request is missing a valid API key.

Having this data outside of the function would be useful in passing it to the next function in the process.

How to migrate from a wordpress to a javascript project?

I’m a junior web developer just starting an internship.
I learned web development for 6 months (basic frontend HTML CSS, and specialised in backend with node.js and postgreSQL).

The project of my internship is to migrate a wordpress project to a javascript one

What would be my options to do it ?

My main issue is that I don’t understand how a wordpress project is structured and where I can find data of the project to migrate it to postgreSQL and strapi.

I was thinking about using next.js as framework and strapi with postgreSQL for the db.

The problem for me right now is that i don’t know anything about wordpress. And it is difficult to understand by retro-engineer a wordpress project with MySQL db to migrate to a js one.

I’ve located some key files like the wp-config.php (which contains db connection, theme definition), schema.php (which contains db creation structure), and a data dictionary which declare data types for csv data export file.

If you have any idea, i’m listening thank you !

How to prevent ‘ResizeObserver loop completed with undelivered notifications.’-error with React in mui/material/Table?

This is the code we use:

import Table from '@mui/material/Table';
import TableBody from '@mui/material/TableBody';
import TableCell from '@mui/material/TableCell';
import TableContainer from '@mui/material/TableContainer';
import TableHead from '@mui/material/TableHead';
import TableRow from '@mui/material/TableRow';

import TextField from '@mui/material/TextField';

export type ResizeObserverErrorProperties = object;

export function ResizeObserverError(props: ResizeObserverErrorProperties) {
    return (
        <TableContainer>
            <Table>
                <TableHead></TableHead>
                <TableBody>
                    <TableRow key="description">
                        <TableCell>
                            <TextField
                                id={'description'}
                                value={
                                    'Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.'
                                }
                                fullWidth
                                multiline
                            />
                        </TableCell>
                    </TableRow>
                </TableBody>
            </Table>
        </TableContainer>
    );
}

export default ResizeObserverError;

When the browser is resized we get the following error:

Uncaught runtime errors:
ERROR
ResizeObserver loop completed with undelivered notifications.
    at handleError (http://localhost:4200/psa/vendor.js:113137:58)
    at http://localhost:4200/psa/vendor.js:113156:7

We tried:

  • removing ‘fullWidth’:
    The error is gone, but the textfield is not broad enough
  • removing ‘multiline’:
    The error is gone, but the text is only in one line
  • adding ‘rows={4}’:
    The error is gone, but the field is always 4 rows high, even there is no text
  • adding ‘minRows={3}’:
    The error is still there
  • adding ‘maxRows={10}’:
    The error is still there

Gulpjs wait for async function before continue

I cut gulpfile.js into several files. My purpose is to share the data with various tasks. And I use windows system, gulp 5 and “type”: “module” config.

The file structure is given below:

gulpfile.js
tasks/clean.js
tasks/deploy_data.js
data/path.js
data/other.js

gulpfile.js

import gulp from 'gulp';
import clean from './tasks/clean.js';
import deploy_data from './data/deploy_data.js';

global.data = {}; // share data with all tasks.

function deploy_at_start() {
  gulp.series(deploy_data);
}

deploy_at_start(); // I hope that deploy_data will be executed before any task I debug, because each task needs to use the contents of data.

console.log(data); // {} Blank, obviously deploy_data has not been completed yet, I want the code below to be executed only after it completes.

export {
  clean,
  // alot of other tasks
};

./tasks/clean.js

function clean(cb) {
  console.log(data.path.src); // I need to get some information from data, such as the path I want to delete.
  cb();
}

export default clean;

The point is this

data/path.js

const path = {
  src: './folder/*',
};

export default path;

tasks/deploy_data.js

import path from 'node:path';
import { pathToFileURL } from 'node:url';

async function deploy_data(cb) {
  const dir = path.join(process.cwd(), 'data');
  const files = fs
.readdirSync(dir, { withFileTypes: true }).filter((item) => item.isFile())
.map((item) => item.name); // I have a lot of data files, so this is the easier way to get all the data

  for (const file of files) {
    data[path.parse(file).name] = (await import(pathToFileURL(path.join(dir, file)).href)).default;
  }

  cb();
}

export default deploy_data;

When I execute gulp clean, I can’t get the data.path information. I think it may be because deploy_data is async and something went wrong.

From the terminal, I can see that deploy_data completes its work after clean is completed, which is why data is empty.

I understand that I can use gulp.series to execute deploy_data before clean, but I have a huge amount of data. I think I can achieve the goal by executing deploy_data once at the beginning of gulpfile.js similar to the current method.

In the above case, is there a way for me to execute deploy_data before executing any gulp task (the task that has been exported) and wait for it to complete before executing other code?