How to delete a file only after a user fully downloads it in Node.js (Express) with partial resume capability?

I have an Express route that serves user-uploaded encrypted media files. I want to delete the file only after the user has fully downloaded it. However, my current implementation deletes the file even when the download is interrupted or partially completed.

app.get('/uploads/:folder/*', authenticateToken, (req, res, next) => {
    try {
        const { folder } = req.params; // Get the folder name dynamically
        const paths = path.join('uploads', folder, req.params[0]);
        const filePath = path.join(MEDIA_ROOT_PATH, paths); // Get the full file path
        
        fs.stat(filePath, (err, stats) => {
            if (err) {
                if (err.code === 'ENOENT') { // File not found
                    return res.status(404).send('File not found');
                }
                return next(err);
            }

            const readStream = fs.createReadStream(filePath);
            res.set({
                'Content-Type': 'application/octet-stream',
                'Content-Disposition': `attachment; filename="${path.basename(filePath)}"`,
                'Content-Length': stats.size,
                'Cache-Control': 'no-store',
                'Pragma': 'no-cache',
                'Expires': '0'
            });

            readStream.pipe(res);

            // Delete file after the response stream ends
            readStream.on('end', () => {
                fs.unlink(filePath, (err) => {
                    if (err) {
                        console.error('Error deleting the file:', err);
                    } else {
                        console.log('File deleted successfully');
                    }
                });
            });

            // If the user cancels the request, stop the stream
            req.on('close', () => {
                readStream.destroy();
            });

        });
    } catch (error) {
        res.status(500).send('Error fetching file');
    }
});

React useContext State Updated Not Triggering useEffect [duplicate]

I am attempting to implement the React useContext hook to share the state of a user license. I’ve found this pattern online but can’t seem to get it to work. If the license is not valid, the user is redirected to a warning page with instructions.

I have these files;

license-context.tsx

import { createContext, useContext, useState, useEffect } from "react";

interface Props {
    children: React.ReactNode;
}

export interface LicenseContextModel {
    product: boolean | null;
    api: string | null;
    isLoading: boolean;
}

export const LicenseContext = createContext<LicenseContextModel>({} as LicenseContextModel);

const LicenseContextProvider = ({ children }: Props): JSX.Element => {
    const [product, setProduct] = useState(false);
    const [api, setApi] = useState('');
    const [isLoading, setIsLoading] = useState(true);

    useEffect(() => {
        const checkLicense = async () => {
            try {
                console.log('LicenseContextProvider is running');
                
                setProduct(true);
                setApi('blah');

            } catch (error) {
                console.error('License check failed:', error);
            }
            setIsLoading(false);
        };

        checkLicense();
    },[]);

    const licenseContext: LicenseContextModel = {
        product,
        api,
        isLoading,
    };

    console.log('licenseContext', licenseContext);

    return <LicenseContext.Provider value={licenseContext}>{children}</LicenseContext.Provider>;
};

export function useLicense(): LicenseContextModel {
    const context = useContext(LicenseContext);

    console.log('context', context);

    if (!context) {
        throw new Error('useLicense must be used within a LicenseContextProvider');
    }

    return context;
}

export default LicenseContextProvider;

LandingPage.tsx

import React, { useEffect } from "react";

import LicenseContextProvider, { useLicense } from '@/contexts/license-context';
import { useRouter } from 'next/navigation';

const LandingPage = () => {
  const { product, api, isLoading } = useLicense();
  const router = useRouter();

  useEffect(() => {
      console.log('page isLoading', isLoading);
      
      if (!isLoading) {
        console.log('product', product);
        console.log('api', api);
  
        if (!product) {
          router.push('/license-warning');
        } else if (api === '') {
          router.push('/key-manager');
        }
      }
    },[product, api, isLoading]);
  
  return (
    <>
      <title>Landing Page</title>
      <LicenseContextProvider>
        <div className="w-full">
          <div className="flex flex-col w-full">
            <p>Landed on the page</p>
          </div>
        </div>
      </LicenseContextProvider>
    </>
  );
};

export default LandingPage;

LandingPage imports LicenseContextProvider and useLicense from license-context.
The values for product, api, and isLoading are retrieved from the license context using the useLicense() call which uses LicenseContext as the initial context.

The useEffect in LandingPage listens for changes to product, api, and isLoading.

When the component LicenseContextProvider is loaded, it’s useEffect sets the product and api values to true and ‘blah’ respectively and sets isListening to false. However, the useEffect in LandingPage is never triggered by any of the changes and so the call is always routed to the license-warning page.

It seems that there is no connection between LicenseContext and LicenseContextProvider. I’m trying to figure out how to share the state between them.

The console log from the browser shows this;

context Object {  }                                     license-context.tsx:57:13
licenseContext                                          license-context.tsx:42:12
  Object { product: false, api: "", isLoading: true }
LicenseContextProvider is running                       license-context.tsx:25:33
page isLoading undefined                                    LandingPage.tsx:22:21
product undefined                                           LandingPage.tsx:24:25
api undefined                                               LandingPage.tsx:25:25
licenseContext                                          license-context.tsx:42:12
  Object { product: true, api: "blah", isLoading: false }

I would expect to see another ‘page isLoading’ update after the licenseContext useEffect finishes but the useEffect in LandingPage is not triggered.

Any suggests are appreciated. I feel like I am missing a basic link between the LicenseContext (which is always undefined) and the LicenseContextProvider (which is updating the product, api, and isLoading states).

TypeError: this[#browser].sessionSubscribe is not a function

I’m using webDriver.io with cucumber to automate mobile apps

this is my package.json file

{
  "name": "webdriverio-appium-cucumber-boilerplate",
  "license": "MIT",
  "scripts": {
    "code:check": "yarn code:lint && yarn code:prettier",
    "code:format": "yarn code:lint --fix --quiet && yarn code:prettier --write",
    "code:lint": "eslint .",
    "code:prettier": "prettier --check "**/*.js*"",
    "report:allure": "npx allure",
    "report:generate": "yarn report:allure generate --clean ./test-report/allure-result/ -o ./test-report/allure-report",
    "report:open": "yarn report:allure open test-report/allure-report",
    "android.app": "npx wdio ./config/wdio.android.app.conf.js",
    "ios.app": "npx wdio ./config/wdio.ios.app.conf.js",
    "bs.app": "npx wdio ./config/wdio.bs.app.conf.js --debug",
    "android.sauce.rdc.app": "npx wdio ./config/saucelabs/wdio.android.rdc.app.conf.js",
    "ios.sauce.rdc.app": "npx wdio ./config/saucelabs/wdio.ios.rdc.app.conf.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/Schveitzer/webdriverio-appium-cucumber-boilerplate.git"
  },
  "dependencies": {
    "@babel/cli": "^7.7.0",
    "@babel/core": "^7.7.2",
    "@babel/node": "^7.7.0",
    "@babel/polyfill": "^7.7.0",
    "@babel/preset-env": "^7.7.1",
    "@babel/register": "^7.7.0",
    "@types/node": "^12.12.7",
    "@wdio/allure-reporter": "^9.6.3",
    "@wdio/globals": "^9.7.3",
    "@wdio/local-runner": "^9.7.3",
    "@wdio/spec-reporter": "^9.6.3",
    "allure-commandline": "^2.13.0",
    "archiver": "^7.0.1",
    "axios": "^1.7.9",
    "chokidar": "^4.0.3",
    "debug": "^4.1.1",
    "eslint": "^6.6.0",
    "eslint-config-airbnb": "^18.0.1",
    "eslint-config-airbnb-base": "^14.0.0",
    "eslint-config-prettier": "^6.5.0",
    "eslint-plugin-import": "^2.18.2",
    "husky": "^3.0.9",
    "nconf": "^0.12.1",
    "nodemailer": "^6.9.16",
    "prettier": "^1.19.1",
    "webdriverio": "^9.7.3"
  },
  "devDependencies": {
    "@cucumber/cucumber": "^11.2.0",
    "@wdio/browserstack-service": "^9.7.3",
    "@wdio/cli": "^9.7.3",
    "@wdio/cucumber-framework": "^9.7.3",
    "appium": "^2.15.0",
    "chai": "^5.1.2"
  },"overrides": {
    "@cucumber/cucumber": "^11.2.0"
  }
}

dont know where im going wrong , but im constantly getting this error :

TypeError: this[#browser].sessionSubscribe is not a function

I tried updating all the dependencies to a compatible level but that didn’t worked out .

What can I do if 308 is encountered during the request

Using a technology stack called vue3, I called two services, I also configured two proxies, but when I asked for the interface again I opened the console, first a 308 redirection, the redirection reported an error.I use mostman to call the interface and return the data normally, someone help meenter image description here
enter image description here

The response is normal. Normal value is returned

Button without obvious onclick event

I’m reposting this as despite what was claimed the question does not have other answers and the proposed ones are not related to it.

I’m looking at elements which don’t have an obvious onclick event registered. I was pointed to the fact there is an event registered in the DOM but there was no seeing from the code how it was done.

An example is Linktree profiles like this one (don’t worry, the links are long dead and sfw) which have buttons that when you click on them the link is constructed and it opens it but the elements don’t specify the data used to construct it in any obvious way.

Example: the link constructed is http://example.fake but neither the button element nor its container elements have any obvious data associated with it indicating http://example.fake as the link url.

I don’t expect anybody to have the solution and will likely have to implement my own but on the chance that someone can answer it in future I’m leaving the question here.

Again to make this clear, and in case it wasn’t clear to everyone in the original, the questions are:

  1. With the elements appearing generic and with no “id” identifier how does it link the correct url to the action?
  2. What method is used to register the event listeners specific to these elements?

Disable shadow effect option in APS forge viewer

Does anyone know if it is possible to set the option “Disable shadow effect” (previously called “Smooth Navigation”) programatically?

disable shadow effect ui

I tried the options below from the GuiViewer3D documentation but none seem to set that switch.

viewer.setOptimizeNavigation(true);
viewer.setGroundShadow(false);

convert a Map of promises and return a promise of a map of settled promises

I feel like I’m hitting a fundamental limitation of functional programming but wondered if anyone could prove me wrong:

describing this concisely is difficult, so bear with me

I have a map of promises, e.g.:

const namedPromises = {
  database: promise1 as Promise<HealthInfo>,
  someApi: promise2 as Promise<HealthInfo>,
  // ...
} as Record<string, Promise<HealthInfo>>;

The use case for this is health reporting for a service (think calling a /health endpoint and it calls other endpoints/dependencies for their health)

And I want to convert it into a Promise that returns a map of settled promises like so:

function async someMethod<T>(namedPromises: Record<string, Promise<T>>): Promise<Record<string, PromiseSettledResult<T>>> {
  // ...magic...

  // i know the result will be more generic but this is for example's sake.
  return {
    database: promiseSettled1 as PromiseSettledResult<T>,
    someApi: promiseSettled2 as PromiseSettledResult<T>,
  };
}

I am aware of the function Promise.allSettled that takes an array of Promises and returns an array of settled ones, however in order to wrap each named entry of the namedPromises record into a promise, i must call .then and map the result like this:

i provide a key with both resolved and rejected results to know which promise it refers to.

const wrapped = Object.entries(namedPromises).map(([key, promise]) => { 
  return promise.then(
    (value) => ({
      key,
      result: {
        status: 'fulfilled',
        value,
      } as PromiseFulfilledResult<HealthInfo>,
    }),
    (reason) => ({
      key,
      result: {
        status: 'rejected',
        reason,
      },
    }),
  );
});

Here-in lies the main problem. This meta result is also a Promise, implying it can also reject even though it clearly doesn’t (apart from timeouts which we can handle with a Promise.race([promise, timeoutPromise]). see full example below). The type system doesn’t know any better. Rejected promises don’t know what key they relates to, as that ‘key‘ information is hidden within a successfully resolved promise.

I feel this is a fundamental limitation of functional programming somehow – an instrinsic logistical limitation around named promises that could fail – but i can’t quite justify that feeling with proof.

I find my solution to this to be rather clunky, I filter the top level (wrapped) settled-promise list by fulfilled results only, then return the inner map. Below is an example of my code with this workaround, My question is whether typescript affords a more elegant means of accomplishing this task?

Here is my current solution in full, including timeouts:

  async allSettledDependencies(
    dependencyHealthReporters: Record<string, Promise<HealthInfo>>,
    timeoutPerDependency: number = 1000, // ms
  ): Promise<Record<string, PromiseSettledResult<HealthInfo>>> {
    const withTimeout = (
      key: string,
      promise: Promise<HealthInfo>,
    ): Promise<{ key: string; result: PromiseSettledResult<HealthInfo> }> => {
      const timeoutPromise = new Promise<HealthInfo>((_, reject) =>
        setTimeout(
          () =>
            reject(new Error(`Timeout exceeded: ${timeoutPerDependency}ms`)),
          timeoutPerDependency,
        ),
      );

      // allow dependencies to timeout individually to increase resilience of health function.
      return Promise.race([promise, timeoutPromise]).then(
        (value) => ({
          key,
          result: {
            status: 'fulfilled',
            value,
          } as PromiseFulfilledResult<HealthInfo>,
        }),
        // this will be either the timeout rejection, or the rejected promise.
        (reason) => ({
          key,
          result: {
            status: 'rejected',
            reason,
          },
        }),
      ) as Promise<{ key: string; result: PromiseSettledResult<HealthInfo> }>;
    };

    const settledEntries = await Promise.allSettled(
      Object.entries(dependencyHealthReporters).map(
        ([dependencyName, promise]) => withTimeout(dependencyName, promise),
      ),
    );

    return Object.fromEntries(
      settledEntries
        // we rely on all promises being fulfilled at the `withTimeout` function for this logic to work.
        .filter((topSettled) => topSettled.status === 'fulfilled')
        .map(({ value }) => [
          value.key,
          // either returns the resolved health info or converts the rejection error into an 
          this.healthInfoFromSettledResult(value.result),
        ]),
    );
  }

Some related thoughts:

  • Is there a way of saying “Trust me bro,These all resolve?” other than as unknown as PromiseFulfilledResult<...> for the wrapped results?`
  • I could call Promise.all instead of Promise.allSettled if I’m confident about the garunteed settlement of the wrapped promises, something feels smelly about this though.

passing false to Promise.all [duplicate]

I’ve seen code like that and wonder how it works ? according to MDN Promise.allSettled expects an array of Promises but here it is passed false for one of them and seems to ignore it. Is this kind of code safe to use ?

let log = async x => console.log(x)

let flag = false

let main = async () => {
  await Promise.allSettled([ flag && log(0), log(1) ])
}

main()

JavaScript URL.canParse() Exception

I’m looking for a way to check if a given string is a valid URL. I came across URL.canParse(), which solves my problem quite nicely. However, it is falsely flagging the string “USA: Gulf of Mexico” as a URL, when it is obviously not. I assume it’s attempting to flag it as a mailto URL, but I’m still confused as to exactly why it thinks that is a mailto.

Is there a check I could make to avoid this edge case, or is there a “better” way to check if a URL is valid? I specifically need to get a boolean check, because I am using React and need to change the HTML tag I use depending on whether it’s a valid URL or not.

Cookies not being passed to backend (FastApi) from front end (react)

I have 2 cookies set from FastAPI like:

    RESPONSE.set_cookie(
        key="access_token",
        value=ACCESS_TOKEN_FINAL,
        httponly=True,  
        secure=True,   
        max_age=3600,  
        expires=time.time() + 3600, 
        samesite="none"  
    )

Both of which I can see in my browser. However, when I try to call a session check;

@AUTH_ROUTER.get("/checkSession")
async def checkSession(request: Request):    
    AdvancedLogging(f"checkSession called")
    AdvancedLogging(f"Request.cookies all: {request.cookies.get('*')}")

I can see no cookies are sent. CORS is set up correctly, and I call the APi with:

export async function isAuthenticated() {
    try {
        const response = await fetch("http://127.0.0.1:8000/auth/checkSession", {
            method: "GET",
            credentials: "include", 
            headers: {
                "Content-Type": "application/json",
            },
        });

        const data = await response.json();

        if (response.ok) {
            console.log("User is authenticated:", data);
            return true; // User is authenticated
        } else {
            console.error("User is not authenticated");

            // If the backend returns a "redirect" field, use it to redirect the user
            if (data.redirect) {
                window.location.href = data.redirect; // Redirect to the dynamically provided login URL
            }
            return false; // User is not authenticated
        }
    } catch (error) {
        console.error("Error during authentication check:", error);
        return false; // Return false on error
    }
}

I feel like I am going insane, has anyone got any suggestions?

My backend cors incase it helps:

## CORS Middleware
app.add_middleware(
    CORSMiddleware,
    allow_origins=[IsScoped("FRONTEND_URL")], 
    # allow_origins=["*"], 
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"]
)

ChakraUI custom theme w recipe, not shown in component from snippet

I am trying to update the theme, with some custom colors for components. IE: I want my default buttons to be a specific shade of blue. So i followed the docs and added semantic tokens such as:

import { createSystem, defaultConfig, defineConfig } from '@chakra-ui/react';

import { buttonRecipe } from './receipes/button';

export const buttonRecipe = defineRecipe({
  base: {
    display: 'flex',
  },
  variants: {
    visual: {
      solid: { bg: 'red', color: 'white' },
      outline: { borderWidth: '1px', borderColor: 'blue.400' },
    },
    size: {
      sm: { padding: '4', fontSize: '12px' },
      lg: { padding: '8', fontSize: '24px' },
    },
  },
});

export const config = defineConfig({
  theme: {
    recipes: {
      button: buttonRecipe,
    },
    tokens: {
      colors: {
        red: { value: '#CB4022' },
        green: { value: '#01ca96' },
        orange: { value: '#FCAF45' },
        brand: {
          200: { value: '#6EB5F7' },
          400: { value: '#0E70F1' },
          900: { value: '#1F211F' },
        },
      },
    },
    semanticTokens: {
      colors: {
        error: { value: '{colors.red}' },
        success: { value: '{colors.green}' },
        warning: { value: '{colors.orange}' },
        brand: {
          solid: { value: '{colors.brand.400}' },
          contrast: { value: '{colors.brand.200}' },
        },
      },
    },
  },
});

export const system = createSystem(defaultConfig, config);

I also use the snippet from Chakra to create the Button component which looks generates:

import type { ButtonProps as ChakraButtonProps } from '@chakra-ui/react';
import {
  AbsoluteCenter,
  Button as ChakraButton,
  Span,
  Spinner,
} from '@chakra-ui/react';
import * as React from 'react';

interface ButtonLoadingProps {
  loading?: boolean;
  loadingText?: React.ReactNode;
}

export interface ButtonProps extends ChakraButtonProps, ButtonLoadingProps {}

export const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
  function Button(props, ref) {
    const { loading, disabled, loadingText, children, ...rest } = props;
    return (
      <ChakraButton disabled={loading || disabled} ref={ref} {...rest}>
        {loading && !loadingText ? (
          <>
            <AbsoluteCenter display="inline-flex">
              <Spinner color="inherit" size="inherit" />
            </AbsoluteCenter>
            <Span opacity={0}>{children}</Span>
          </>
        ) : loading && loadingText ? (
          <>
            <Spinner color="inherit" size="inherit" />
            {loadingText}
          </>
        ) : (
          children
        )}
      </ChakraButton>
    );
  },
);

When I build my web app with NextJS, the <Button /> color is not reflected regardless of the variant being solid or outline. I tried adding recipe to the button, but it didn’t render either.

What do I need to do so that the colors &/or recipe is picked up correctly?

UpdateOne in mongodb returns matchedCount:0 and modifiedCount:0 [closed]

Hello I’m sorry because I am new in mongodb. I’ve tried everything on internet and
I gave up by not finding anything running well. Here’s my code

import { MongoClient, ObjectId } from "mongodb";

// Update file
const client = await MongoClient.connect("mongodb://localhost:27017", {
  useNewUrlParser: true,
  useUnifiedTopology: true,
});

// specify the DB's name
const db = client.db("cookiemonster");

// Update file
await db
  .collection("mahasiwswa")
  .updateOne(
    {
      _id: new ObjectId('67a22acb53d63e1c1cb973e3')
    },
    { $set: { nama: "Haydiras", email: "[email protected]" }, },
  )
  .then((res) => {
    console.log(res);
  })
  .catch((err) => {
    console.log(err);
  });

// close connection
client.close();

But I got this result and nothing updated:

{
  acknowledged: true,
  modifiedCount: 0,
  upsertedId: null,
  upsertedCount: 0,
  matchedCount: 0
}

Here is my document on MongoDB Compass
enter image description here

What things am I missing? Thank you for your help..

Dynamic image rendering in Vue not working. How do I plug image link into src dynamically?

I am trying to dynamically render an image in Vue where the picture url is being passed as part of a prop object but cannot get it to work for the life of me.

ArtistCard.vue

<template>
  <div>
    <img :src="artist.pictureUrl" alt="artist-picture" />
  </div>
</template>

<script setup>
const { artist } = defineProps(["artist"]);
</script>

App.vue

<template>
  <div>
    <artist-card :artist="{name: "Alex Waves", pictureUrl:"@/assets/images/artist1.jpeg"}" />
  </div>
</template>
<script setup>
import ArtistCard from "@/components/ArtistCard.vue"
</script>

When I hard code the link it seems to work but I can’t get it to dynamically render?

Any help would be greatly appreciated

Login example for telegram’s tdweb wrapper

I’m trying to create a small telegram client using TDLib (Telegram Database library). They offer an npm package that has TDLib prebuilt called tdweb but i cannot find any examples that show how to use the library. I have been looking at this github repo that has a complete telegram client web app developed with tdweb and React but i would like to see if there are other resources. Does anyone know how to use this library?