简体   繁体   中英

how should I handle this nodejs code to do the rigth things?

this is my first question here. I need some help with my code structure. My api in node with express have to do the following: receipt GET /api/file/{filename} return the file content, its could be a big one (a few GB). For now, I could get the files with streams, but I don't the best practice to handle error in this case.

'use strict';
const fs = require('fs'); 
const express = require('express');
const app = express();
const path = require('path');
const filePath = path.join(__dirname, `../file`);




console.log(filePath)

app.get('/api/:filename', (req, res) => {
  let filename = req.params.filename
  const streamFile = fs.createReadStream(`${filePath}/${filename}`);
  streamFile.pipe(res);
} );


module.exports = app;

Should I make another dir, maybe 'modules', and there code an async function to read and pipe the files, and call the function from app.get in routes dir?

Remember that Express is an "un-opinionated, minimalist web framework for Node.js applications", unopinionated means that it doesn't decide for you a lot of aspects of what tool you use for each specific task, and that is the main difference with another frameworks like Rails. Said that, you could use the classical and and old try and catch , in this case around your I/O operation. A module is a way to mantain separation of concerns and it's a way to organize your code so you can fastly identify what is the part of your code that is causing a malfunction. So in this case i don't consider it necessary because your router's callback is doing one thing and that is ok.

app.get('/api/:filename', (req, res) => {
  let filename = req.params.filename
  try{
      const path = `${filePath}/${filename}`;
      if (!fs.existsSync(path)) return res.status(404).send('You could send any message here...');
      const streamFile = fs.createReadStream(path);
      streamFile.pipe(res);
  } catch {
      res.status(500).send();
  };
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM