gpt4 book ai didi

javascript - 如何在 Node js Controller 文件中引用 Elastic Search JavaScript 客户端库

转载 作者:行者123 更新时间:2023-12-03 00:15:42 25 4
gpt4 key购买 nike

我正在express框架中做node.js RESTapi。我想将 Elasticsearch 集成到我的项目中。因此,我安装了 Elastic Search JavaScript 客户端库,并将这些代码添加到 app.js 中。

var client = new elasticsearch.Client({
host: 'localhost:9200',
log: 'trace'
});

client.ping({
requestTimeout: 30000,
}, function (error) {
if (error) {
console.error('elasticsearch cluster is down!');
} else {
console.log('All is well');
}
});

我得到了“一切都很好”。但是我如何在我的 Controller 文件中引用这个客户端。

最佳答案

传递参数:

将变量作为参数传递给导入函数,这样您就可以将变量从一个文件传递到另一个文件。

//app.js
var client = new elasticsearch.Client({
host: 'localhost:9200',
log: 'trace'
});
var catRouters = require("categorry.controller.js")(client);

// categorry.controller.js
module.exports = function (client) {
....
return { create, read, update, readById, categoriesByCity, live_search };
};

使用全局变量:

将变量设置为 Node.js 全局对象以在其他文件中使用,Node.js 全局对象本质上是全局的,并且在所有模块中都可用。

//app.js
var client = new elasticsearch.Client({
host: 'localhost:9200',
log: 'trace'
});
global.client = client;

// categorry.controller.js
....
consoel.log(global.client);

关于javascript - 如何在 Node js Controller 文件中引用 Elastic Search JavaScript 客户端库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54530426/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com