existsSync не находит файл
Почему fs.existsSync(localConfigPath) не может увидеть файл, а require(localConfigPath) видит?
src/common/Config/Config.ts:
import IConfig from './IConfig';
import * as fs from 'fs';
let Configurator: IConfig;
const baseConfigPath: string = '../../../data/config.json';
const localConfigPath: string = '../../../data/config.local.json';
console.log('is exist: ' , fs.existsSync(localConfigPath), require(localConfigPath));
if (fs.existsSync(localConfigPath)) {
Configurator = require(localConfigPath);
} else {
Configurator = require(baseConfigPath);
}
export default Object.freeze(Configurator);
src/index.ts:
import Config from './common/Config/Config';
const app: express.Application = express();
console.log(Config);
package.json:
{
"name": "project",
"version": "0.0.1",
"scripts": {
"fast_buld": "tsc && node public/index.js",
"start": "node public/index.js",
"build": "tsc",
"tslint": "tslint -p tsconfig.json"
},
"dependencies": {
"body-parser": "^1.19.0",
"express": "^4.17.1",
"fs": "0.0.1-security",
"ip": "^1.1.5",
"mongoose": "^5.9.15",
"mysql2": "^2.1.0",
"path": "^0.12.7"
},
"devDependencies": {
"@types/express": "^4.17.6",
"@types/node": "^14.0.1",
"tslint": "^6.1.2",
"typescript": "^3.9.2"
}
}
tsconfig.json:
{
"compilerOptions": {
"module": "commonjs",
"target": "es5",
"lib": ["es5"],
"sourceMap": true,
"noUnusedLocals": true,
"noImplicitAny": true,
"removeComments": true,
"preserveConstEnums": true,
"strict": true,
"outDir": "public",
"rootDir": "src",
"allowSyntheticDefaultImports": true
},
"exclude": [
"node_modules"
]
}
структура проекта:
|
|-- data
| |-- config.json
| |-- config.local.json
|-- src
| |-- common
| | |-- Config
| | | |--Config.ts
| |--index.ts
|-- public
| |-- common
| | |-- Config
| | | |--Config.js
| |--index.js
|--package.json
|--tsconfig.json
Ответы (1 шт):
Автор решения: Yugofx
→ Ссылка
Из документации Node.js:
Относительные пути будут разрезолвлены относительно текущей рабочией директории, определенной
process.cwd().
Поскольку процесс вы запускаете из рутовой директории, то путь будет разрешен относительно нее, а не папки с конфигом в ./src/common/Config.
Для того, чтобы разрешить путь относительно директории файла Config.ts, воспользуйтесь модулем path.
const path = require('path');
const fs = require('fs');
// ...
if (fs.existsSync(path.resolve(__dirname, localConfigPath))) {
Configurator = require(localConfigPath);
} else {
Configurator = require(baseConfigPath);
}