2

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) {



  }
};
Peter Pik
  • 11,023
  • 19
  • 84
  • 142

2 Answers2

3

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.

Michael Troger
  • 3,336
  • 2
  • 25
  • 41
1

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.

Nir Levy
  • 12,750
  • 3
  • 21
  • 38