0

Brief

I'm trying to import a file containing redundant's code in consumers. So far it seems my file is doesn't read by the consumer which returns me:

function getAsync is not defined

but it however defined in file1.js

Here my snippet:

file1.js:

const redis=require("redis"); 
rejson = require('redis-rejson');
const {promisify} = require('util'); 

rejson(redis); /* important - this must come BEFORE creating the client */
let client= redis.createClient({
    port:6380,
    host:'localhost',
    // password:process.env.rPass
});  

const setAsync = promisify(client.json_set).bind(client);
const arrappendAsync = promisify(client.json_arrappend).bind(client);
const getAsync = promisify(client.json_get).bind(client); 
const existsAsync= promisify(client.exists).bind(client);

file2.js:

require("./redisConnect")
async function getUser(){ 
    let res=await getAsync("userStock", ".")
        .catch((err) => console.error(err)); 
    resArray= JSON.parse(res)
    console.log("userStock res: ", resArray[0]);
    client.quit()
}

// use userId to filter relevant array 
getUser()

So how handle this situation?

Any hint would be great, thanks

vsemozhebuty
  • 12,992
  • 1
  • 26
  • 26
Webwoman
  • 10,196
  • 12
  • 43
  • 87

1 Answers1

0

In file1.js, you need to do:

module.exports = getAsync;

Then in file2.js, do this:

var getAsync = require('./file1.js')
Matt Kuhns
  • 1,328
  • 1
  • 13
  • 26
  • I would just pour the file1 in the file2, I have seen is possible using packages like babel and for example this question on stackoverflow for basic use case: https://stackoverflow.com/questions/36426770/node-js-require-without-storing-it-into-a-variable – Webwoman Mar 04 '19 at 21:20
  • I don't understand your concern. Yes, requiring a file will execute the code in the file. Generally we use export/require to modularize code, so we can reuse it in other files. – Matt Kuhns Mar 04 '19 at 21:33
  • well, I would to be able to make this kind of stuff: https://stackoverflow.com/a/39286176/9817602 – Webwoman Mar 04 '19 at 21:46