NodeJS模块中数据文件的相对路径

我创建了一个用打字稿编写的NodeJS模块(尽管它不应更改任何内容)。

它的组织方式如下:

.
├── data/
│   └── MY_DATA_FILES.json
│
├── src/
│   ├── data/
│   │   └── data.ts
│   │
│   └── OTHER_TYPESCRIPT_FILES.ts
│
├── dist/
│   ├── data/
│   │   └── data.js
│   │
│   └── OTHER_JAVASCRIPT_FILES.ts
│
├── package.json
└── tsconfig.json

My goal is to read the data files from the data.ts file. When my current working directory in on the root of the module it's not a problem (then it would be ./data/...) but when I use this as a module, and it's placed in the nodes_modules/ directory, I'm not sure how to handle the situation.

我目前正在按以下方式读取文件:

import fs from 'fs';
const basePath = './data';
const filesPath = 'subdirectory/my_data.json';

export function getData(): any {
    const fileFullPath  = basePath + '/' + filesPath;
    const contents = fs.readFileSync(fileFullPath);

    // [...]
}

But here, my basePath is dependent on my working directory. I could set it as ./node_modules/my_module/data, but I know that's not the right approach..

任何帮助,将不胜感激,谢谢!

评论
  • 薄荷情
    薄荷情 回复

    You would typically build a path for each location that is relative to the directory where your code is located and access the desired location in a relative way from that. The location of your code will be passed to the code's module as __dirname. You can then combine that relative path with __dirname to build a full path to the target location without making any assumptions about where or how the module is installed.

    So, assuming your code is in the src directory, that would be where __dirname points to. To, get access to the data directory below the src directory, you would use:

    let srcDataDir = path.join(__dirname, "data");
    

    To get access to the dist/data directory, you would use:

    let distDataDir = path.join(__dirname, '../dist/data');
    

    To get access to the higher level data directory where MY_DATA_FILES.json is, you would use:

    let topDataDir = path.join(__dirname, '../data');
    

    As, you can see, the key is to build everything relative from the location you do know which is __dirname passed to the code as the location of the code's own directory.

    In Javascript's modules, you don't ever want to make any assumptions about the current working directory because that can literally be anything. That's controlled by the top level program itself and how the program was started and is not anything the module itself can rely on or make assumptions about. But __dirname will always be the full path to the directory where your module's code is running from.