2017-03-26 231 views
1

查看CouchDB 1.6.1 here的文檔,提到可以使用JS require(path)函數。你怎麼做到這一點?文檔中說path是「從設計文檔根開始的CommonJS模塊路徑」。如何在map函數中使用require()?

我的設計文檔叫_design/data。我已經上傳的附件,以這種所謂的test.js設計文檔,可以在/_design/data/test.js訪問,並且包含下面的代碼:

exports.stuff = function() { 
    this.getMsg = (function() { 
     return 'hi'; 
    })() 
} 

但在我的地圖功能如下代碼:

function(doc) { 
    try { 
    var x = require('test.js'); 
    } catch (e) { 
    emit ('error', e) 
    } 
} 

結果這個錯誤:

["error", "invalid_require_path", "Object has no property \"test.js\". {\"views\":{\"lib\":null},\"_module_cache\":{}}"] 

看起來require正在尋找的路徑作爲對象param ...但我不明白爲什麼如果是這樣。

看着this鏈接,描述了在舊版本的CouchDB的這一特徵,它說,你可以:

However, in the upcoming CouchDB 1.1.x views will be able to require modules provided they exist below the 'views' property (eg, 'views/lib/module')

,並給出了下面的代碼示例:

{ 
    "_id": "_design/example", 
    "lib": { 
     // modules here would not be accessible from view functions 
    }, 
    "views": { 
     "lib" { 
      // this module is accessible from view functions 
      "module": "exports.test = 'asdf';" 
     }, 
     "commonjs": { 
      "map": function (doc) { 
       var val = require('views/lib/module').test; 
       emit(doc._id, val); 
      } 
     } 
    } 
} 

但這並沒有工作對於我在CouchDB 1.6.1上。我得到的錯誤:

{message: "mod.current is null", fileName: "/usr/share/couchdb/server/main.js", lineNumber: 1137, stack: "([object Array],[object Object])@/usr/share/couchdb/server/main.js:1137\n([object Array],[object Object])@/usr/share/couchdb/server/main.js:1143\n([object Array],[object Object],[object Object])@/usr/share/couchdb/server/main.js:1143\n(\"views/lib/module\")@/usr/share/couchdb/server/main.js:1173\n([object Object])@undefined:3\n([object Object])@/usr/share/couchdb/server/main.js:1394\n()@/usr/share/couchdb/server/main.js:1562\[email protected]/usr/share/couchdb/server/main.js:1573\n" 

回答

1

在你的問題中,你沒有提供函數作爲串。這不是太容易發現,但必須在將函數存儲到CouchDB中之前將其功能串聯起來(手動或使用.toString())。 Caolan在你鏈接的文章中有這個錯誤。

+0

謝謝。你的意思是在test.js中嗎? –

+0

不,在你的問題。這是它應該如何的(在這裏註釋不能更好地格式化):''commonjs「:{」map「:」function(doc){var val = require('views/lib/module')。test ; emit(doc._id,val);}「}' –

0

使用這個例子:

15 views: { 
    16  lib: { 
    17  foo: "exports.bar = 42;" 
    18  }, 
    19  test: { 
    20  map: "function(doc) { emit(doc._id, require('views/lib/foo').bar); }" 
    21  } 
    22 } 

發現在這裏年長的CouchDB文檔:https://wiki.apache.org/couchdb/CommonJS_Modules

我有一個例子工作。不知道有什麼區別是真的...我運行'臨時'的意見,而不是保存,但我不知道爲什麼會影響require聲明

相關問題