ESM import.meta All In One

发布时间 2023-08-27 00:09:00作者: xgqfrms

ESM import.meta All In One

获取 ES Module 的 meta 原数据

import.meta

The import.meta meta-property exposes context-specific metadata to a JavaScript module.
It contains information about the module, such as the module's URL.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/import.meta

使用场景

  • 使用 ESM 在 Node.js 中实现 __dirname 功能, 获取模块所在的文件夹绝对路径
  • ...
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
console.log(`✅ import.meta.url =`, import.meta.url, typeof import.meta.url)
console.log(`✅ __filename =`, __filename, typeof __filename)
console.log(`✅ __dirname`, __dirname, typeof __dirname)

image

demos

ESM 中实现 __dirname

import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
// import fs from 'fs';
// import path from 'path';
// import { fileURLToPath } from 'url';

// create one custom `__dirname`, because it doesn't exist in es-module env.
// use `import.meta.url` to get the current module's URL, ✅
// then get the module's folder absolute path 
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const dir = path.resolve(path.join(__dirname, 'upload');

if (!fs.existsSync(dir)) {
  fs.mkdirSync(dir);
}

// OR
if (!fs.existsSync(dir)) {
  fs.mkdirSync(dir, {
    mode: 0o744, // Not supported on Windows. Default: 0o777
  });
}

CJS __dirname

const fs = require('fs');
const path = require('path');

const dir = path.resolve(path.join(__dirname, 'upload');

if (!fs.existsSync(dir)) {
  fs.mkdirSync(dir);
}

// OR
if (!fs.existsSync(dir)) {
  fs.mkdirSync(dir, {
    mode: 0o744, // Not supported on Windows. Default: 0o777
  });
}

(? 反爬虫测试!打击盗版⚠️)如果你看到这个信息, 说明这是一篇剽窃的文章,请访问 https://www.cnblogs.com/xgqfrms/ 查看原创文章!

node:fs vs fs

import fs from 'node:fs';

import fs from 'fs';

node: 类似 https://, file:// 是一种通信协议 ❓

refs

https://stackoverflow.com/questions/21194934/how-to-create-a-directory-if-it-doesnt-exist-using-node-js/71735771#71735771

https://stackoverflow.com/questions/67554506/what-are-the-nodefs-nodepath-etc-modules



©xgqfrms 2012-2021

www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!

原创文章,版权所有©️xgqfrms, 禁止转载 ?️,侵权必究⚠️!