{"id":4688,"date":"2022-11-24T11:18:32","date_gmt":"2022-11-24T03:18:32","guid":{"rendered":"https:\/\/www.ookangzheng.com\/?p=4688"},"modified":"2022-11-24T11:18:34","modified_gmt":"2022-11-24T03:18:34","slug":"nodejs-module-__dirname-not-found-solution","status":"publish","type":"post","link":"https:\/\/www.ookangzheng.com\/nodejs-module-__dirname-not-found-solution\/","title":{"rendered":"Nodejs module __dirname not found solution"},"content":{"rendered":"\n

Why<\/h2>\n\n\n\n

__dirname is not defined in ES module scope, thats why error shows up<\/p>\n\n\n\n

Solution<\/h2>\n\n\n\n

You first need to import the Node.js path<\/code> module and the fileURLToPath<\/code> function from the url<\/code> module:<\/p>\n\n\n\n

import path from 'path';\nimport { fileURLToPath } from 'url';\n<\/code><\/pre>\n\n\n\n

Then you can replicate the functionality of __dirname<\/code> in this way:<\/p>\n\n\n\n

const __filename = fileURLToPath(import.meta.url);\n\nconst __dirname = path.dirname(__filename);\n<\/code><\/pre>\n\n\n\n

This, incidentally, also replicates __filename<\/code>, which returns the filename of the code which is executed.<\/p>\n\n\n\n

Now you can use __dirname<\/code> as usual:<\/p>\n","protected":false},"excerpt":{"rendered":"

Why __dirname is not defined in ES module scope, thats why error shows up Solution You first need to import…<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[43,33],"tags":[],"_links":{"self":[{"href":"https:\/\/www.ookangzheng.com\/wp-json\/wp\/v2\/posts\/4688"}],"collection":[{"href":"https:\/\/www.ookangzheng.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.ookangzheng.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.ookangzheng.com\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.ookangzheng.com\/wp-json\/wp\/v2\/comments?post=4688"}],"version-history":[{"count":1,"href":"https:\/\/www.ookangzheng.com\/wp-json\/wp\/v2\/posts\/4688\/revisions"}],"predecessor-version":[{"id":4689,"href":"https:\/\/www.ookangzheng.com\/wp-json\/wp\/v2\/posts\/4688\/revisions\/4689"}],"wp:attachment":[{"href":"https:\/\/www.ookangzheng.com\/wp-json\/wp\/v2\/media?parent=4688"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.ookangzheng.com\/wp-json\/wp\/v2\/categories?post=4688"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.ookangzheng.com\/wp-json\/wp\/v2\/tags?post=4688"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}