javascript - 如何在 map 函数中使用 require() ?

标签 javascript view couchdb require

查看 CouchDB 1.6.1 的文档 here ,其中提到可以使用 JS require(path) 函数。你怎么做到这一点?文档说 path 是“从设计文档根开始的 CommonJS 模块路径”。

我的设计文档名为_design/data。我已经上传了一个名为 test.js 的设计文档附件,可以在 /_design/data/test.js 访问该附件,并包含以下代码:

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

但是我的 map 函数中的以下代码:

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 正在寻找 docparam 中的对象路径...但我不明白为什么会这样。

查看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\n@/usr/share/couchdb/server/main.js:1573\n"

最佳答案

在您的问题中,您没有以字符串形式提供该函数。这不太容易发现,但您必须在将函数存储到 CouchDB 之前对它们进行字符串化(手动或使用 .toString())。 Caolan 在您链接的帖子中存在该错误。

关于javascript - 如何在 map 函数中使用 require() ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43034283/

相关文章:

ios - 从另一个 View 类重新加载 Collection View 数据

ajax - 过滤时,如何发布 SearchModel,但在 View 中获取不同的 ResultsModel

json - 如何在 couchdb View 中调用另一个 View ?

couchdb - 使用ElasticSearch索引CouchDB View

node.js - 带有 CouchDB 附件的服务文件?

javascript - 如何向传单 map 添加叠加层?

javascript - 无法在 WordPress UI 中解析 json 字符串

ios - 我是否必须为 rootviewController 实现一个 View 来管理其他 Controller ,但自己不显示任何内容?

javascript - 如何在 node.js 中使用原型(prototype)

javascript - Protractor - 发送规范/套件名称作为参数