How do I call a function from another file?

1.9k views Asked by At

Call a function from another file doesn't work on my JS file. I can't call a function from another js file.I think the problem is between connecting two files.

my first JS file

    const { response } = require('express');
var express = require('express');
const {render}=require('../app');
const productHelpers = require('../helpers/product-helpers');
var router = express.Router();
var productHelper=require('../helpers/product-helpers')





/* GET users listing. */
router.get('/', function(req, res, next) {

  productHelpers.getAllProduct().then((products)=>{
    
    res.render('admin/veiw-products', { admin: true, products })
  })

});
router.get('/add-product', function (req, res) {
  res.render('admin/add-product')

})

router.post('/add-product', (req, res) => {
  console.log(req.body)
  console.log(req.files.image)
  productHelpers.addProduct(req.body, (id) => {
    console.log(id)
    let image = req.files.image
    image.mv('./public/product-images/' + id + '.jpg', (err, done) => {
      if (!err) {
        res.render('admin/add-product')

      }else{
        console.log(err);
      }
    })


  })
})
router.get('/delete-product/:id',(req,res)=>{
  let proId=req.params.id
  console.log(proId);
  productHelpers.deleteProduct(proId).then((response)=>{
    res.redirect('/admin/')
  })
  
})


module.exports = router;

my second JS file

    var db = require('../config/connection')
var collection = require('../config/collections');
const {Delete} = require('../routes/admin');
module.exports = {



    addProduct: (product, callback) => {
        console.log(product);
        db.get().collection('product').insertOne(product).then((data) => {

            callback(data.ops[0]._id)

        })
    },

    getAllProduct:()=>{
        return new Promise(async(resolve,reject)=>{
            let products=await db.get().collection(collection.PRODUCT_COLLECTION).find().toArray()
            
            
            
            resolve(products)

        }) 
    },
    deleteProduct:(prodId)=>{
        return new Promise((resolve,reject)=>{
            db.get().collection(collection.PRODUCT_COLLECTION).removeOne({_id:prodId}).then((response)=>{
               console.log(response)
                resolve(response)
            })
        })
    }
    
}

my error report

    productHelpers.getAllProduct is not a function
TypeError: productHelpers.getAllProduct is not a function
    at C:\Users\sainupangad\Desktop\newproject\routes\admin.js:15:18
    at Layer.handle [as handle_request] (C:\Users\sainupangad\Desktop\newproject\node_modules\express\lib\router\layer.js:95:5)
    at next (C:\Users\sainupangad\Desktop\newproject\node_modules\express\lib\router\route.js:137:13)
    at Route.dispatch (C:\Users\sainupangad\Desktop\newproject\node_modules\express\lib\router\route.js:112:3)
    at Layer.handle [as handle_request] (C:\Users\sainupangad\Desktop\newproject\node_modules\express\lib\router\layer.js:95:5)
    at C:\Users\sainupangad\Desktop\newproject\node_modules\express\lib\router\index.js:281:22
    at Function.process_params (C:\Users\sainupangad\Desktop\newproject\node_modules\express\lib\router\index.js:335:12)
    at next (C:\Users\sainupangad\Desktop\newproject\node_modules\express\lib\router\index.js:275:10)
    at Function.handle (C:\Users\sainupangad\Desktop\newproject\node_modules\express\lib\router\index.js:174:3)
    at router (C:\Users\sainupangad\Desktop\newproject\node_modules\express\lib\router\index.js:47:12)

another report

 [nodemon] starting `node ./bin/www index.js`
express-session deprecated undefined resave option; provide resave option app.js:27:9express-session deprecated undefined saveUninitialized option; provide saveUninitialized option app.js:27:9
(node:7424) Warning: Accessing non-existent property 'render' of module exports inside circular dependency
(Use `node --trace-warnings ...` to show where the warning was created)
Database connected
(node:7424) Warning: Accessing non-existent property 'getAllProduct' of module exports inside circular dependency
GET /admin 500 62.505 ms - 4079
2

There are 2 answers

3
Blessing Mwale On BEST ANSWER

Try to use

const { getAllProduct } = require('../helpers/product-helpers');
0
fotiecodes On

The best and most efficient way to call a function from another file is to export it from the host file before importing and using it in the target file. You just need to make sure the function you are trying to import was actually exported in the host file. Here's an example following your question;

my first JS file

export default function getAllProduct(){
  // some piece of code here!

}

my second JS file

import getAllProduct from "'../helpers/product-helpers'";

You'll notice that from the above i have just one single function in the first file, reason why i exported it directly at the declaration level, in a real life scenario, we might have plenty of those. what you can do is simply write your functions and at the end of the file you export each and everyone of them, or just those you wish to use out of the host file.

A typical example could be seen below:

//  say.js
 function sayHi(user) {
   alert(`Hello, ${user}!`);
  }

 function sayBye(user) {
   alert(`Bye, ${user}!`);
  }

 export {sayHi, sayBye}; // a list of exported functions

...then import and use them in your target file as below;

//  main.js
import {sayHi, sayBye} from './say.js';

sayHi('John'); // Hello, John!
sayBye('John'); // Bye, John!

But if there’s a lot to import, we can import everything as an object using import * as <obj>, for instance:

//  main.js
import * as say from './say.js';

say.sayHi('John');
say.sayBye('John');