2017-03-27 22 views
-1

我不得不修改基本的Node.js文件上的代码,以使其工作,我想知道为什么?基本Node.js“功能”vs“=>”表示法

失败:

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

这个工程:

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

错误:

/my-app/tmp/hello2.js:6 var 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:945:3

完整代码

const http = require('http'); 

const hostname = '127.0.0.1'; 
const port = 3000; 

//const server = http.createServer((req, res) => { 
// above *wont work*?? below works 
var server = http.createServer(function(req, res){ 
    res.statusCode = 200; 
    res.setHeader('Content-Type', 'text/plain'); 
    res.end('Hello World\n'); 
}); 

// server.listen(port, hostname,() => { 
// above *wont work*?? below works 
server.listen(port, hostname, function() { 
    console.log(`Server running at http://${hostname}:${port}/`); 
}); 
+0

什么错误? –

+0

你得到了什么错误,你使用的是哪个版本的节点? – Skabbi

+0

/my-app/tmp/hello2.js:6 var server = http.createServer((req,res)=> { } SyntaxError:意外令牌> at Module._compile(module.js:439:25 )module.load(module.js:356:32) at Function.Module._load(module.js:312:12)处的Object.Module._extensions..js(module.js:474:10) 处的 at function.Module.runMain(module.js:497:10) at startup(node.js:119:16) at node.js:945:3 –

回答

1

这是因为你的Node.js不作为标准支持ES6的一些功能

两种解决方案

  1. 你必须编辑您的package.json

    { 
        "dependencies": { 
        "babel-cli": "^6.0.0", 
        "babel-preset-es2015": "^6.0.0" 
    }, 
    "scripts": { 
        "start": "babel-node --presets es2015 app.js" 
    } 
    } 
    

    和运行npm start

    有关更多信息:How to run Node.js app with ES6 features enabled?

  2. 更新您的Node.js

    $ sudo npm cache clean -f 
    $ sudo npm install -g n 
    $ sudo n stable 
    
+3

我认为更新到更新版本的Node应该足够了,在任何稳定版本的Node中都肯定支持箭头功能。 – DatBassie

+0

这是肯定的另一个解决方案。我会编辑我的答案 – mk2