__dirname là đường dẫn tuyệt đối đến thư mục chứa file đang chạy, __filename là đường dẫn đến chính file đó.
Cả hai resolve từ vị trí file, không phải từ process.cwd().
js
// đúng: đọc được template bất kể app chạy từ thư mục nào
path.join(__dirname, 'templates', 'email.html')
// sai: resolve từ process.cwd(), lệch khi chạy từ nơi khác
'./templates/email.html'Trong ES Modules (file .mjs hoặc type: module trong package.json) hai biến này không tồn tại, phải dựng lại từ import.meta.url:
js
import { fileURLToPath } from 'url'
import { dirname } from 'path'
const __filename = fileURLToPath(import.meta.url)
const __dirname = dirname(__filename)