Documentation for Fastify, as well as for all official Fastify plugins, uses the older Node CommonJS module syntax. You can however, make use of ES modules.
To use ES modules in Node, you can set "type": "module"
in your package.json. Then, instead of const fastify = require('fastify')({ logger: true })
you can do:
import Fastify from 'fastify';
const fastify = Fastify({ logger: true });
The same is true for the official plugins:
import fastifyFormbody from 'fastify-formbody';
fastify.register(fastifyFormbody);
__dirname
and __filename
One difference between CommonJS modules and ES modules is that __filename
and __dirname
are not available in ES modules. As the official Node docs suggest, they can be replicated with via import.meta.url
import path from 'path';
import { fileURLToPath } from 'url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
import fastifyStatic from 'fastify-static';
fastify.register(fastifyStatic, {
root: path.join(__dirname, 'public'),
prefix: '/public/',
});
Top comments (0)