Jatin Mehrotra
Jatin Mehrotra

Reputation: 11513

How to import entire file contents in express?

I want to avoid repitition of code so that is why i want to import file.

dynamodb.js file contents

var AWS = require("aws-sdk");
    require('dotenv').config()
    let awsConfig = {
        "region": process.env.DBREGION,
        "endpoint": process.env.DBENDPOINT,
        "accessKeyId": process.env.DBACCESSKEYID, "secretAccessKey": process.env.DBSECRETACCESSKEY
    };
    AWS.config.update(awsConfig);
    let docClient = new AWS.DynamoDB.DocumentClient();

my code for scan.js file

require("./db/dynamodb")
let fetchOneByKey = function () {
   
    var params = {
        TableName: "employees",
        Key: {
            "employeeIDI want something like this ": "1"
        }
    };
    docClient.get(params, function (err, data) {
        if (err) {
            console.log("users::fetchOneByKey::error - " + JSON.stringify(err, null, 2));
        }
        else {
            console.log("users::fetchOneByKey::success - " + JSON.stringify(data));
        }
    })
}


fetchOneByKey();

when i run scan.js file it says ReferenceError: docClient is not defined

Upvotes: 0

Views: 32

Answers (2)

Molda
Molda

Reputation: 5704

You can export the docClient and then when you use require you get the instance like this:

//dynamodb.js
....

module.exports = new AWS.DynamoDB.DocumentClient();

then use it in any file:

// any-file.js

const docClient = require("./db/dynamodb");

Upvotes: 1

Tuan Anh Tran
Tuan Anh Tran

Reputation: 7237

docClient is not defined in scan.js. that's why you got the above error

you will need to module.exports in dynamodb.js and then require it in scan.js

Upvotes: 1

Related Questions