This tutorial is compatible with Hapi v17.8.1
The Inert plugin provides a wide range of functionality to work with files in routes in Hapi.
First of all you need to install the Inert module to your app using NPM or Yarn and register it before your server will start.
You can install it in terminal using the next commands:
npm i inert -s //OR
yarn add inert
The example of simple app:
'use strict';
const Hapi = require('hapi');
const server = Hapi.server({
port: 3000,
host: 'localhost'
});
server.route({
method: 'GET',
path: '/file',
handler: (req, res) => {
return 'File';
}
});
const init = async () => {
await server.register(require('inert'));
await server.start();
console.log(`Server running at: ${server.info.uri}`);
};
process.on('unhandledRejection', (err) => {
console.log(err);
process.exit(1);
});
init();
To send a file in the Hapi there is a method “res.file()”. The first argument its the path to file, the second argument to pass an options. To send a file in Hapi as an attachment we need to pass the “mode: ‘attachment’” in options object:
handler: (req, res) => {
return res.file('image.png', {
mode: 'attachment'
});
}
Server will send this “image.png” as an attachment and user will receive it to “Downloads” folder in browser. An example of app:
'use strict';
const Hapi = require('hapi');
const server = Hapi.server({
port: 3000,
host: 'localhost'
});
server.route({
method: 'GET',
path: '/file',
handler: (req, res) => {
return res.file('image.png', {
mode: 'attachment'
});
}
});
const init = async () => {
await server.register(require('inert'));
await server.start();
console.log(`Server running at: ${server.info.uri}`);
};
process.on('unhandledRejection', (err) => {
console.log(err);
process.exit(1);
});
init();
To show this “image.png” in browser we can just call the “res.file” method without “options” argument:
handler: (req, res) => {
return res.file('image.png');
}
//OR
handler: (req, res) => {
return res.file('image.png', { mode: false });
}
If we want to override the filename we can use the “filename” property of “options”:
handler: (req, res) => {
return res.file('image.png', {
mode: 'attachment',
filename: 'another-name.png'
});
}
For example, to send the pre-compressed version of the file, we can use the “lookupCompressed” property of “options”:
handler: (req, res) => {
return res.file('image.png', {
mode: 'attachment',
filename: 'another-name.png',
lookupCompressed: true
});
}
Learning Hapi.js? Buy my Hapi.js Handbook🔥
comments powered by Disqus