├── data/
│   └── MY_DATA_FILES.json
├── src/
│   ├── data/
│   │   └── data.ts
│   │
├── dist/
│   ├── data/
│   │   └── data.js
│   │
├── 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.