[英]Unable to read config.json file in node.js
我正在为编写单元测试用例,有关链接的问题提到了如何使用sinon存根/模拟需要nodejs的子模块
当我包括一个需求
const index=require('./index.js');
它里面有一个图书馆要求
const library= require('./library.js');
library.js文件具有读取config.json文件的要求(在上面的index.js中也需要此配置文件),如下所示
const readConfig = require('read-config');
const config = readConfig('./config.json');
我已经尝试了以上链接中建议的多种方法,但是我失败了
const stubs = {
'./library': function (response) {
assert.equal(some, null);
return 'Some ' + argument;
},
'../library1.js': {
function(paths, opts){
var config='./config.json'
return config;
}
},
}
const index=proxyquire('./index.js',stubs)
当我运行单元测试用例时,仍然出现以下错误
throw configNotFound(configPath);
^
ReadConfigError: Config file not found: ./config.json
我想知道我严重丢失了代码的哪一部分,导致代码抛出错误
我正在尝试编辑index.js和所有相关文件,其中使用以下代码读取配置
var path = require('path');
var pathToJson = path.resolve(__dirname, '../config.json');
// Load config
var config = fs.readFile(pathToJson , 'utf8', function (err, data) {
if (err) throw err;
config = JSON.parse(data);
});
这里的挑战是我无法更改节点代码
您的问题很可能是路径解析。 如果./config.json
是相对于您从( process.cwd()
)运行Node的位置,那么它将起作用。 如果它与您的库模块有关,则可以执行以下操作:
// Works for JS and JSON
const configPath = require.resolve('./config.json');
// Works in general
const configPath = require('path').join(__dirname, 'config.json');
// Then
const readConfig = require('read-config');
const config = readConfig(configPath);
如果不了解更多有关项目布局以及如何启动应用程序的信息,很难说是否是这种情况。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.