[Node.js] Handle Relative Paths in a Node.js ESM Project with import.meta.url

Our CLI can be run from anywhere on the system but we have a critical error. The script is trying to find a data.json file that is relative to where it is being called. This will throw an error if you aren't actually in the script directory.

The fix for this in an ECMAScript project like we are in is to use a import.meta.url variable that will give use the directory that the script is executed in. We can append our data.json to this path and call that throughout our script and we've fixed our error!

 

import {fileURLToPath} from "url";
import {dirname, join} from "path";

console.log(import.meta.url) // file:///Users/xxxxxx/Documents/learning/cli-tools/service.js
// in CommonJS, you can get the filename by __filename
console.log(fileURLToPath(import.meta.url)) // /Users/xxxxxx/Documents/learning/cli-tools/service.js
// in CommonJS, you can get the dirname by __dirname
console.log(dirname(fileURLToPath(import.meta.url))) // /Users/xxxxxx/Documents/learning/cli-tools

const __dirname = dirname(fileURLToPath(import.meta.url));
const dataFile = join(__dirname, "data.json");

 

posted @   Zhentiw  阅读(77)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2021-08-05 [Unit Testing + Jest + Node server] Testing a Node middleware with Jest
2021-08-05 [Unit testing + Jest] Use jest-in-case to Reduce Duplication and Improve Test Titles
2021-08-05 [Unit testing] Improve Error Messages by Generating Test Titles
2021-08-05 [Typescript] Extends and override an existing interface
2021-08-05 [SAA + SAP] 20. Other services - 1 (StackSets, EMR, SWF, Opsworks, WorkSpaces)
2016-08-05 [AngularJS] Accessible Button Events
2016-08-05 [React Native] Complete the Notes view
点击右上角即可分享
微信分享提示