首页 > 解决方案 > 节点:语法错误:意外的令牌(

问题描述

我正在搞砸的这个节点模块出现以下错误。关于为什么语法错误的任何想法?运行以下命令后出现以下错误:

node ./tester.js ./test.js
//test.js

var Test = (function () {

    add: function(num) {
        return num + num;
    };


 })();
if (module.exports) {
    module.exports = Test;
}

// tester.js

var testModule = process.argv[2],
    TestAdd = require(testModule);
console.log(TestAdd);

//OUTPUT 

    add: function(num) {
                 ^

SyntaxError: Unexpected token (

标签: javascriptnode.js

解决方案


这是一个明显的语法错误。您必须返回对象。

var Test = (function () {
   return {
      add: function(num) {
          return num + num;
      }
   }   
})();

或者返回函数

var Test = (function () {
   const add = function(num) {
       return num + num;
   }

   return add; 
})();

推荐阅读