[Node.js] Trigger a File Download in Express
2023-09-14 08:59:16 时间
Downloading and saving a file is a common scenario when building out your web application. Using Express, you can either trigger a download from an existing file or set the headers on the response to send a file you created through Node. This lesson walks you through both approaches.
If the file is already exists on the server:
const express = require('express') const app = express() app.get('/', (req, res) => { res.download('./test.txt'); })
If files is not there:
app.get("/", (req, res) => { res.setHeader( "Content-disposition", "attachment; filename=message.json" ) res.setHeader("Content-type", "application/json") res.send(JSON.stringify({message: "Hello"})) })
相关文章
- 【nodejs原理&源码赏析(7)】【译】Node.js中的事件循环,定时器和process.nextTick
- Node.js进程管理之Process模块
- [CLI] Create a Single-Command Node.js CLI with Oclif, TypeScript and Yarn Workspaces
- [Node.js] Show More Lines in a Node.js Error Stack Trace
- [Tools] Create a Simple CLI Tool in Node.js with CAC
- [Node.js] Testing ES6 Promises in Node.js using Mocha and Chai
- [Node.js] Use "prestart" in scripts
- [Whole Web, Node.js, PM2] Restarting your node.js app on code change using pm2
- [Node.js] Using npm link to use node modules that are "in progress"
- [Node.js] Serve a random static file with Express
- [Tools] Create a Simple CLI Tool in Node.js with CAC
- [Node.js] Create a model to persist data in a Node.js LoopBack API
- [Node.js] Exporting Modules in Node
- [Whole Web, Node.js, PM2] Restarting your node.js app on code change using pm2
- 用 webpack 构建 node 后端代码,使其支持 js 新特性并实现热重载
- Node.js TLSSocket 库里涉及到的证书链的概念简介
- 带你了解Node.js包管理工具:包与NPM
- Node.js(二)node 核心模块 fs、HTTP模块、express框架
- 12-安装node.js和webpack的完整步骤
- Docker学习笔记17:docker实例之安装 Node.js、PHP、MySQL、Tomcat、Python、Redis、MongoDB、Apache