webserverrenderbun

How to save images to Render Disk by using Web Service BunJs


I'm having trouble saving pictures to the Render Disk.

  1. I set up the BanJs Web Server on the Render service and opened the Disk with the /var/lib/data router

  2. Then configured the server and started everything successfully. My app.ts:

const STORE_PATH = '/var/lib/data';
const PORT: number = +(process.env.PORT ?? 8080);
const NODE_ENV = process.env.NODE_ENV ?? 'development';

const server = Bun.serve({
  port: PORT,
  async fetch(req) {
    const url = new URL(req.url);
    
    if (req.method !== 'POST') {
      return new Response(null, { status: 405 });
    }

    if (!req.body) {
      return new Response(null, { status: 400 });
    }

    const filePath = `${STORE_PATH}/image.jpg`;
    await Bun.write(filePath, await Bun.readableStreamToBlob(req.body));
    return new Response(null, { status: 201 }
  },
  error() {
    return new Response(null, { status: 500 });
  },
});

console.log(`[${NODE_ENV}] Listening on port ${server.port}`);
  1. When sending a post request with a file via Postman, the server gives status 201 but does not save the file to the Render Disk.

Question: Who has experience in setup, where am I wrong or where is the problem?


Solution

  • Here is my solution:

        import { fileURLToPath } from 'url';
        import path, { dirname } from 'path';
    
        const STORE_PATH = '/var/lib/data';
        const __filename = fileURLToPath(import.meta.url); 
        const dirPath = path.resolve(`${dirname(__filename)}/../`);
        
        ...
    
          const storePath = NODE_ENV === 'development' ? dirPath : STORE_PATH
          const folderPath = `${folderPath}/images`;
          const filePath = `${folderPath}/${name}`;
    
          const file = await Bun.file(filePath);
          const isFileExists = await file.exists();
                
          if (isFileExists) {
             ...
          } 
    
          await Bun.write(filePath, image); 
    
        ...
    

    To check if the file exists, you can use the Render terminal and use SCP or Magic Wormhole to check if it is saved correctly.

    In order to get the image by Get request, you can use the following code:

       const app = new Elysia()
         .get('/images/:imagePath', async ({ params: { imagePath }}) => {
             const storePath = NODE_ENV === 'development' ? dirPath : STORE_PATH
             const folderPath = `${folderPath}/images`;
             const filePath = `${folderPath}/${imagePath}`;
        
             const file = await Bun.file(filePath);
             const isFileExists = await file.exists();
        
             if (isFileExists) {
               return file;
             } else {
               return {
                 status: 'failed',
                 message: 'File not found',
               };
             }
           }
         )