在 Node.js 中,可以使用 response.sendFile
方法来设置文件路径并将文件发送到客户端。这个方法接受一个文件路径作为参数,并在服务器上查找该文件。例如:
app.get('/download',function(request, response) {
response.sendFile(__dirname + '/files/myfile.txt');
});
这段代码会在服务器上查找位于 /files
目录下的 myfile.txt
文件,并将其发送到客户端。
注意,在使用 response.sendFile
方法时,文件路径必须是绝对路径。如果使用相对路径,可以使用 __dirname
变量,它会返回当前执行脚本所在的目录的绝对路径。
另外,还可以使用 response.sendFile
方法的第二个参数来指定文件的 options,例如指定文件名、设置 HTTP 头信息等。
例如:
app.get('/download', function(request, response) {
response.sendFile(__dirname + '/files/myfile.txt', {
headers: {
'Content-Disposition': 'attachment; filename=myfile.txt'
}
});
});
这段代码会在下载文件时设置 HTTP 头信息,使得文件以附件的形式下载,并指定文件名为 myfile.txt
。