0

I'm trying to run a script using Puppeteer framework. (I'm a relative newbie to software). Every time I try to run, I get the error below. I'm sure nothing is wrong with the code as it worked fine an a different machine earlier. This error is noted right as main.js makes the (only) function call.

SyntaxError: Invalid or unexpected token
    at new Script (vm.js:80:7)
    at createScript (vm.js:274:10)
    at Object.runInThisContext (vm.js:326:10)
    at Module._compile (internal/modules/cjs/loader.js:664:28)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:712:10)
    at Module.load (internal/modules/cjs/loader.js:600:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:539:12)
    at Function.Module._load (internal/modules/cjs/loader.js:531:3)
    at Function.Module.runMain (internal/modules/cjs/loader.js:754:12)
    at startup (internal/bootstrap/node.js:283:19)
var puppeteer = require('puppeteer');
var $ = require('cheerio');
const url = 'https://www.reddit.com/controversial/';
​
puppeteer
  .launch()
  .then(function(browser) {
    return browser.newPage();
  })
  .then(function(page) {
    return page.goto(url).then(function() {
      return page.content();
    });
  })
  .then(function(html) {
    $('h2', html).each(function() {
        console.log($(this).text());
        console.log('\r\n');
    });
    })
  .catch(function(err) {
    //handle error
  });

I've uninstalled, cleaned, reinstalled Node.js as per this link (How do I completely uninstall Node.js, and reinstall from beginning (Mac OS X))

waterbottle
  • 1
  • 1
  • 3

1 Answers1

5

This isn't actually related to puppeteer at all. On line 4, you have a zero width space character, which doesn't look like anything, but makes your Node program invalid. This sometimes shows up if you're copying a line from a site or some other source.

If you delete that line and insert a blank new line, you should be fine. I tested by copying out your code, installing the dependencies, and running it. Depending on your editor, you should be able to show unexpected unicode characters like this.

Zac Anger
  • 3,159
  • 1
  • 9
  • 29
  • wow, thank you. that fixed it! how did you spot that? i'd never come across that before – waterbottle Apr 12 '19 at 01:43
  • I have my editor (Vim) set to show unicode characters, using [this Vim plugin](https://github.com/vim-utils/vim-troll-stopper), so as soon as I copied your code into Vim it showed up. There's probably a plugin or config to get that to work for your editor, depending on what you use. I added that to my Vim config because I work with a lot of devs who use Windows, so it's sometimes an issue. – Zac Anger Apr 12 '19 at 01:45