NodeJS Error and when using "="

1

Good afternoon,

People I'm starting my studies with Node.js technology, however when I tried to write the code of a web server example:

const http = require('http');
const hostname = '127.0.0.1';
const port = 3000;

const server = http.createServer((req, res) => {
   res.statusCode = 200;
   res.setHeader('Content-Type', 'text/plain');
   res.end('Hello World\n');
});

server.listen(port, hostname, () => {
   console.log('Server running at http://${hostname}:${port}/');
});

My return generates the following error:

const server = http.createServer((req, res) => {
                                             ^
SyntaxError: Unexpected token >
    at Module._compile (module.js:439:25)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Function.Module.runMain (module.js:497:10)
    at startup (node.js:119:16)
    at node.js:906:3

My Node.js has been downloaded from the GitHub source code (v0.10.29).

NOTE: I have already searched the internet and could not explain anything when using => . I do not understand and if anyone can help me with any reference or explanation I will be grateful to know how => works.

    
asked by anonymous 24.05.2017 / 21:06

2 answers

2

If you use arrow functions you can not use the reserved word function , as you had initially question .

Furthermore, the 0.10.xx version of the Node does not support arrow functions , the full support is only from 6.4.0 summer. You can see the compatibility table here: link

That is:

Wrong:

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

Correct, using arrow functions , using recent versions of Node.js:

const server = http.createServer((req, res) => {

Correct, using function :

const server = http.createServer(function (req, res){
    
24.05.2017 / 21:08
1

The problem is that you are using a very old version of NodeJS

As you said yourself you are using v0.10.29, it is 2014 and it seems to me that only after version 4.4.5 of 2016 has ES6 support been added, which includes the arrow function

    
24.05.2017 / 21:23