What is @hapi/inert?
@hapi/inert is a static file and directory handler plugin for the Hapi.js framework. It allows you to serve static files and directories with ease, making it a useful tool for web applications that need to deliver static content such as images, CSS files, and JavaScript files.
What are @hapi/inert's main functionalities?
Serving Static Files
This feature allows you to serve static files from your server. In this example, a GET request to '/file' will serve the file located at 'path/to/your/file.txt'.
const Hapi = require('@hapi/hapi');
const Inert = require('@hapi/inert');
const init = async () => {
const server = Hapi.server({
port: 3000,
host: 'localhost'
});
await server.register(Inert);
server.route({
method: 'GET',
path: '/file',
handler: {
file: 'path/to/your/file.txt'
}
});
await server.start();
console.log('Server running on %s', server.info.uri);
};
process.on('unhandledRejection', (err) => {
console.log(err);
process.exit(1);
});
init();
Serving Static Directories
This feature allows you to serve static directories. In this example, a GET request to '/directory/{param*}' will serve the files located in 'path/to/your/directory', with 'index.html' as the default file.
const Hapi = require('@hapi/hapi');
const Inert = require('@hapi/inert');
const init = async () => {
const server = Hapi.server({
port: 3000,
host: 'localhost'
});
await server.register(Inert);
server.route({
method: 'GET',
path: '/directory/{param*}',
handler: {
directory: {
path: 'path/to/your/directory',
index: ['index.html']
}
}
});
await server.start();
console.log('Server running on %s', server.info.uri);
};
process.on('unhandledRejection', (err) => {
console.log(err);
process.exit(1);
});
init();
Other packages similar to @hapi/inert
express-static
Express's built-in middleware function to serve static files. It is similar to @hapi/inert but is used within the Express.js framework. It allows you to serve static assets such as HTML files, images, and other files.
koa-static
A static file serving middleware for Koa. It provides similar functionality to @hapi/inert but is designed for the Koa framework. It allows you to serve static files and directories efficiently.
fastify-static
A Fastify plugin for serving static files. It offers similar capabilities to @hapi/inert but is tailored for the Fastify framework. It allows you to serve static files and directories with high performance.