首先搜索path.dirname(process.mainModule.filename)
然后进入目录树../, ../../, ../../../
依此类推,直到找到配置文件。
这是我使用从 rc 窃取的代码(https://github.com/dominictarr/rc https://github.com/dominictarr/rc) 包,它将从名为的文件中读取并解析配置.projectrc
:
const fs = require('fs');
const path = require('path');
// Utils shamefully stolen from
// https://github.com/dominictarr/rc/blob/master/lib/utils.js
find(...args) {
const rel = path.join.apply(null, [].slice.call(args));
return findStartingWith(path.dirname(process.mainModule.filename), rel);
}
findStartingWith(start, rel) {
const file = path.join(start, rel);
try {
fs.statSync(file);
return file;
} catch (err) {
// They are equal for root dir
if (path.dirname(start) !== start) {
return findStartingWith(path.dirname(start), rel);
}
}
}
parse(content) {
if (/^\s*{/.test(content)) {
return JSON.parse(content);
}
return undefined;
}
file(...args) {
const nonNullArgs = [].slice.call(args).filter(arg => arg != null);
// path.join breaks if it's a not a string, so just skip this.
for (let i = 0; i < nonNullArgs.length; i++) {
if (typeof nonNullArgs[i] !== 'string') {
return;
}
}
const file = path.join.apply(null, nonNullArgs);
try {
return fs.readFileSync(file, 'utf-8');
} catch (err) {
return undefined;
}
}
json(...args) {
const content = file.apply(null, args);
return content ? parse(content) : null;
}
// Find the rc file path
const rcPath = find('.projectrc');
// Or
// const rcPath = find('/.config', '.projectrc');
// Read the contents as json
const rcObject = json(rcPath);
console.log(rcObject);
您还可以使用 rc 包作为依赖项npm i rc
,然后在您的代码中:
var configuration = require('rc')(appname, {
// Default configuration goes here
port: 2468
});
这将从名为的文件中读取配置.${appname}rc
.