首页 文章

basic node.js“function”vs“=>”表示法[复制]

提问于
浏览
-1

这个问题在这里已有答案:

我不得不修改基本Node.js文件上的代码,以使其工作,我想知道为什么?

这失败了:

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:意外的令牌>位于Object的Module._compile(module.js:439:25) . Module.load(module.js:356:32)的Module._extensions..js(module.js:474:10)位于Function.Module.runMain的Function.Module._load(module.js:312:12) module.js:497:10)在node.js启动时(node.js:119:16):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}/`);
});

1 回答

  • 1

    这是因为您的Node.js不支持ES6的标准功能

    两种解决方案

    • 您必须编辑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?

    • 更新您的Node.js.
    $ sudo npm cache clean -f
    $ sudo npm install -g n
    $ sudo n stable
    

相关问题