Peter Pik
Peter Pik

Reputation: 11193

call function from other file in express

i'm going to scrape around 20 site and for making it a bit easier i want to divide each scrape function for each site in different documents, however when i do that i keep getting

function scrape(url, callback) {
       ^^^^^^^^^

SyntaxError: Unexpected identifier

in my index i have this

var test = require('../services/test.js');

router.get('/scrape', function(req, res, next) {

  test.scrape("url", function(error){
    if (!error) {
      res.json({succees: "scraped"});
    } else {
      res.json({error: error});
    }

  });

});

and in test.js i have something like this

module.exports = {

  function scrape(url, callback) {



  }
};

Upvotes: 2

Views: 633

Answers (2)

Michael Troger
Michael Troger

Reputation: 3487

You have to write it like:

module.exports = {
    scrape: function(url, callback) {

    }
};

in test.js Then you can call it by test.scrape();

It's simply not valid JavaScript to place a function like you did into an object. You have to specify an index in order to be valid. Alternatively it could also be an array:

module.exports = [
    function scrape(url, callback) {

    }
];

You would call it by test[0](); Note that the name scrape is optional here. Why use named function expressions?

Another option:

module.exports = function (url, callback) {

};

Then you would call it like test();

All that is nothing Node.js specific. You can reproduce the same behavior with standard JavaScript by replacing module.exports of the above examples with var test, accessing the function within the same file.

Upvotes: 3

Nir Levy
Nir Levy

Reputation: 12953

the syntax you should use is:

module.exports = {
  scrape: function(url, callback) {

  }
};

As the module.exports should point to an object, and the function is field on it.

Take a look here, there's a good explanation about it.

Upvotes: 1

Related Questions