Justin
Justin

Reputation: 1

unexpected token node.js v8.9.4

I am just starting out learning node.js (v8.9.4) and I created a simple web server. I am getting the following syntax error message. I understand the => operator is a recent addition to node.js, however I am using the latest stable version. Has anyone else ran into this? Does anyone have any suggestions on things to try to resolve this? The javascript file I am trying to run is below the error message.

SyntaxError: Unexpected token =>
    at createScript (vm.js:80:10)
    at Object.runInThisContext (vm.js:139:10)
    at Module._compile (module.js:607:28)
    at Object.Module._extensions..js (module.js:654:10)
    at Module.load (module.js:556:32)
    at tryModuleLoad (module.js:499:12)
    at Function.Module._load (module.js:491:3)
    at Function.Module.runMain (module.js:684:10)
    at startup (bootstrap_node.js:187:16)
    at bootstrap_node.js:608:3


const http = require('http');

http.createServer(function(req, res) => {
  res.writeHead(200, {
    'Content-Type': 'text/plain'
  });
  res.send('Hello World');
}).listen(3000);

console.log('Server running at http://localhost:3000/');

Upvotes: 0

Views: 378

Answers (2)

Matt Morgan
Matt Morgan

Reputation: 5313

You have a problem here:

http.createServer(function(req, res) => {

Remove the function keyword, or remove the =>. Only one of the two is needed.

(args) => { return do-something-with-args; }

is equivalent to

function(args) { return do-something-with-args; }

There are differences in arrow functions and old-style functions having to do with the definition of this inside the function, but they're not important for your question. In short, this in an arrow function is scoped to the block in which the arrow function is declared (in this case your module,) where with an old-style function, this is scoped to the function itself.

For reference, arrow functions are not particularly "new" to NodeJS. They have been around since ~2015 (v 4.4.5 I think.)

Upvotes: 2

d4vsanchez
d4vsanchez

Reputation: 1994

Try without the function keyword:

http.createServer((req, res) => {
  res.writeHead(200, {
    'Content-Type': 'text/plain'
  });
  res.send('Hello World');
}).listen(3000);

Upvotes: 1

Related Questions