CNode

koa中生成器的问题

问答
Hhuangyanxiong01发布于10 年前最后回复10 年前3 回复4633 浏览0 收藏

  /**
   * generate html with view name and options
   * @param {String} view
   * @param {Object} options
   * @return {String} html
   */
  function *render(view, options) {
    view += settings.viewExt;
    var viewPath = path.join(settings.root, view);
    // get from cache
    if (settings.cache && cache[viewPath]) {
      return cache[viewPath].call(options.scope, options);
    }

    var tpl = yield fs.readFile(viewPath, 'utf8');  //就好象同步执行一样
      console.info(tpl);  //为何这里直接输出就是一个模板的内容,而我按照koa做法,却做不到,
    var fn = ejs.compile(tpl, {
      filename: viewPath,
      _with: settings._with,
      compileDebug: settings.debug,
      open: settings.open,
      close: settings.close
    });
    if (settings.cache) {
      cache[viewPath] = fn;
    }

    return fn.call(options.scope, options);
  }

而我在网上找些资料看了一下,模仿写了一个却做不到

const ejs = require('koa-ejs'),
    path = require('path'),
    thunkify = require('thunkify');
    fs = require('fs'),
    consoleConfig = require('../console/config'),
    read = thunkify(fs.readFile);  // 1

    function *i8ngen(lang){
        var langPath = path.normalize(consoleConfig.savePath + lang + '.' + consoleConfig.outputFileExt);
        yield read(langPath, 'utf8');
    }

    ejs.ejs.filters.i8n = function (code, lang) {
        var i8n = i8ngen(lang);
        i8n.next().value(function (err,data) {
            console.info(data);
            i8n.next(data.toString());
        });
        console.info(i8n.next());
查看回复

回复 (3)

E
elrrrrrrr#1·10 年前

不是很明白问题... 是想在 ejs.esj.filters.i18n 同步读取文件吗? 直接用 readFileSync 不行吗 ? 0.0

F
FoghostCn#3·10 年前

用co包一下再跑,原生的生成器手动调用next太麻烦,koa就是用co包了下,yield后边跟thunkify或者promise

参与回复
登录后即可参与回复。登录