Elasticsearch-js: Opening connection in one file and using it elsewhere

Created on 23 Jul 2019  路  2Comments  路  Source: elastic/elasticsearch-js

Hi all, I am using elasticsearch-js in my application. It works perfectly, except for the fact that I am creating a new connection in about 4 different files instead of using the same connection every time. The code is pretty simple if anyone wants to see it:

var elasticsearch = require('elasticsearch');

var client = new elasticsearch.Client({
    host: 'MY_HOST',
    log: 'LOG'
});

This code is at the top of many files. Is it possible to somehow pass this connection to another file or keep it stored in a different file? It works as is, but I feel like it's terribly inefficient to create that many connections... Thanks!

question

Most helpful comment

Hello!
You are right, it is inefficient, for avoid the issue, you should create the client in one file and share it with the rest of your application :)

// client.js
var elasticsearch = require('elasticsearch');

var client = new elasticsearch.Client({
    host: 'MY_HOST',
    log: 'LOG'
});

module.exports = client
// first.js
var client = require('./client.js')
// second.js
var client = require('./client.js')

All 2 comments

Hello!
You are right, it is inefficient, for avoid the issue, you should create the client in one file and share it with the rest of your application :)

// client.js
var elasticsearch = require('elasticsearch');

var client = new elasticsearch.Client({
    host: 'MY_HOST',
    log: 'LOG'
});

module.exports = client
// first.js
var client = require('./client.js')
// second.js
var client = require('./client.js')

Awesome, thank you! It completely slipped my mind to use module.exports, even though I'm using it elsewhere in my application haha. I haven't implemented it yet, but I'm sure that it'll work so I'll go ahead and close this. Thanks again!

Was this page helpful?
0 / 5 - 0 ratings