查看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"
謝謝。你的意思是在test.js中嗎? –
不,在你的問題。這是它應該如何的(在這裏註釋不能更好地格式化):''commonjs「:{」map「:」function(doc){var val = require('views/lib/module')。test ; emit(doc._id,val);}「}' –