ECMAScriptモジュールを使用しているとき、ノードの中のdirname dirnameの代わりに


調べた通りStack Overflow 私は、使用を示唆するいくつかの解決に遭遇しましたimport.meta.url with fileURLToPath , しかし、言及されなかったことはfileURLToPath "解決"URLを超えているfile:// , ドキュメント自体が示すように url.fileURLToPath ):
fileURLToPath('file:///C:/path/');    // Output:   C:\path\ (Windows)
fileURLToPath('file://nas/foo.txt');  // Output:   \\nas\foo.txt (Windows)
fileURLToPath('file:///你好.txt');    // Output:   /你好.txt (POSIX)
fileURLToPath('file:///hello world'); // Output:   /hello world (POSIX)
ほとんどの場合、ノード固有のものを使用します.外部モジュールではなく、__filename and __dirname ほとんどの場合、完全に不要です.Read (ストリーミング)のネイティブメソッドの大部分(すべてではない) new URL , ノードとして.JSドキュメント自体は以下のように使用します.
  • No __filename or __dirname
  • たとえば、現在のスクリプトと同じレベルのファイルを読む
    import { readFileSync } from 'fs';
    
    const output = readFileSync(new URL('./foo.txt', import.meta.url));
    
    console.log(output.toString());
    
    スクリプトディレクトリ内のすべてのファイルを一覧表示します
    import { readdirSync } from 'fs';
    
    readdirSync(new URL('./', import.meta.url)).forEach((dirContent) => {
      console.log(dirContent);
    });
    
    このメソッドの説明で分かるように、パラメータはサポートされている形式を示します.

  • fs.readFile(path[, options], callback) path <string> | <Buffer> | <URL> | <integer>

  • fs.readFileSync(path[, options]) path <string> | <Buffer> | <URL> | <integer>

  • fsPromises.readdir(path[, options]) path <string> | <Buffer> | <URL>

  • fs.readdir(path[, options], callback) path <string> | <Buffer> | <URL>

  • fs.readdirSync(path[, options]) path <string> | <Buffer> | <URL> | <integer>
  • それでnew URL('<path or file>', import.meta.url) それは解決します、そして、あなたはストリングを扱い、後で連結される変数を作成する必要はありません.

    Note: In the examples I used the synchronous functions just to make it easier to copy and execute.


    あなたが戦略的な瞬間に「必要」のようなものを使うことに興味があるならば、あなたは使うことができます module.createRequire(filename) (ノード12.2.0 +)現在のスクリプトのレベルから異なるレベルのスクリプトをロードするには、次のようにします.
    import { createRequire } from 'module';
    const require = createRequire(import.meta.url);
    
    // foo-bar.js is a CommonJS module.
    const fooBar = require('./foo-bar');
    
    fooBar();
    
    foo-bar.js 目次:
    module.exports = () => {
        console.log('hello world!');
    };