#Help with function with get request

13 messages · Page 1 of 1 (latest)

hot sky
#

so In my get route for express:

app.get('/', async (req: any, res: any) => {

  const images:Array<image> = readFiles()
  try {
    console.log(images)
    res.render('index',{images})
  } catch (err) {
    console.error(err);
    res.status(500).send('Internal Server Error');
  }
});

I load the images array, which updates every time. But because it's called every time, it duplicates each image. How can I change the readfiles function below so that it verifies whether image already exists:

interface image {
    name: Promise<string>;
    id: string ;
    realname: string
}
const images:image[] = []
const directoryPath = path.join(__dirname,'files')
function readFiles(){
  fs.readdir(directoryPath,function readdir(err:string,files:any){
    if(err){
      console.log("Error reading file",err)
      return
    }
    files.forEach(function forFile(file:any){
        console.log(file)
        let newimage: image = {
          name:getSHA256Hash(file),id:randomUUID(),realname:file
        }
        images.push(newimage)

    })
  })
  return images
}
hot sky
#
//I Solved this by creating a Promise function:
interface image {
    name: Promise<string>;
    id: string ;
    realname: string
}
const images:image[] = []
const directoryPath = path.join(__dirname,'files')
function readFiles(): Promise<Array<image>> {
  return new Promise((resolve, reject) => {
    fs.readdir(directoryPath, function readdir(err: string, files: any) {
      if (err) {
        console.log("Error reading file", err);
        return reject(err);
      }

      const newImages: Array<image> = [];

      for (let i = 0; i < files.length; i++) {
        const file = files[i];
        const existingImage = images.find((img) => img.realname === file);

        if (!existingImage) {
          const newImage: image = {
            name: getSHA256Hash(file),
            id: randomUUID(),
            realname: file,
          };
          newImages.push(newImage);
        }
      }

      // Concatenate the newImages array with the existing images array
      const updatedImages = images.concat(newImages);

      resolve(updatedImages);
    });
  });
}
#

and the get index function:

#
app.get('/', async (req: Request, res: Response) => {
  try {
    const updatedImages = await readFiles();
    console.log(updatedImages);
    res.render('index', { images: updatedImages });
  } catch (err) {
    console.error(err);
    res.status(500).send('Internal Server Error');
  }
});
#

Thanks everyone!

#

!resolved

winged hare
#

a few things to improve your code

  • use JS/TS naming conventions; types should use PascalCase, so image becomes Image
  • name your variables in a meaningful way, and place them where they make sense, don't put everything at the highest level, or at a lever higher it actually needs to be
  • don't use Promise<string> for the name of your image, a name is by definition a string, if you're dealing with async code, you should take of that part first
  • you could have used sync methods to have an easier time, tho it will make your code slower, since it will need to wait every time you do an action, but seing you don't have much experience with async JS, I think this will be the best solution for you as of now
#
  • try not to use any in your code, you're not doing yourself a service, since it completely disables type-checking and removes all the information you had about an object (its type)
gaunt oysterBOT
#
ascor8522#0

Preview:```ts
import {Application} from "express"
import * as path from "node:path"
import * as fs from "node:fs"

declare const app: Application

app.get("/", (_req, res) => {
try {
const images = getImages()
console.log(images)
res.render("in
...```

winged hare
#

here is a cleaned up version of your code

#

it should even be easier to understand, with all the async stuff removed

#

the reason your code wasn't working in the first place is because of how callback works
node was calling readdir but wasn't waiting, and returning your images array (still empty) right away

#

your improved code might work, but can also be improved, especially the part with the loop where you try to get the file name