Last updated on July 6, 2023
To download a file from a Node.js server using the Hapi framework, you can utilize the reply.file()
method. Here’s an example of how to implement file download functionality using Hapi:
const Hapi = require('@hapi/hapi');
const Path = require('path');
const server = Hapi.server({
port: 3000,
host: 'localhost'
});
server.route({
method: 'GET',
path: '/download',
handler: (request, h) => {
const filePath = 'path/to/file.txt'; // Replace with the actual file path
return h.file(filePath, {
mode: 'attachment',
filename: Path.basename(filePath)
});
}
});
const startServer = async () => {
try {
await server.start();
console.log('Server running on %s', server.info.uri);
} catch (err) {
console.error('Error starting server:', err);
}
};
startServer();
In the above example, we define a route /download
that handles the file download request. Inside the route handler, we specify the file path of the file to be downloaded.
Using h.file()
, we send the file as a response. The mode
option is set to 'attachment'
to force the browser to download the file rather than displaying it. The filename
option specifies the desired file name for the downloaded file.
Ensure you replace 'path/to/file.txt'
with the actual path to the file you want to download.
When the user visits the /download
URL, the file will be downloaded by the browser with the specified file name.