2017-03-27 6 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サーバ= http.createServer((REQ、RES)=> { ^にSyntaxError:25:439:Module._compile(module.jsで予期しないトークン> )Module.load(module.js:356:32) at Function.Module._load(module.js:312:12)の (Object.Module._extensions..js(module.js:474:10) ) (node.js:119:16) at function.Module.runMain(module.js:497:10) 起動時(node.js:119:16) at node.js:945:3 –

答えて

1

あなたのNode.jsはES6

のいくつかの機能を標準で2つの溶液あなたは

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

あなたのpackage.jsonを編集し、npm startを実行する必要が

  1. をサポートしていないためです

    詳細情報: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

関連する問題