简体   繁体   English

我应该如何处理这个nodejs代码来做正确的事情?

[英]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).我在节点中的 api 必须执行以下操作:receipt GET /api/file/{filename}返回文件内容,它可能很大(几 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?我是否应该创建另一个目录,也许是“模块”,并编写一个异步 function 来读取和 pipe 文件,然后从 app.get 路由中调用 ZC1C425268E68385D1AB5074C17A94F14 文件?

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.请记住,Express 是“用于 Node.js 应用程序的无主见、极简主义 web 框架”,无主见意味着它不会为您决定您为每个特定任务使用什么工具的很多方面,这是与另一个的主要区别Rails 等框架。 Said that, you could use the classical and and old try and catch , in this case around your I/O operation.也就是说,您可以使用经典的和旧的trycatch ,在这种情况下围绕您的 I/O 操作。 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();
  };
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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