在 Node.JS、Jade 模板和 Javascript Options 对象上

On Node.JS, Jade Templates, and Javascript Options Objects

本文关键字:Javascript Options 对象 Node JS Jade      更新时间:2023-09-26

我目前正在Windows中使用node.js构建一个项目。 我正在使用批处理文件来组装资源并通过命令行构建玉模板。 使用 Jade,我正在使用开关 -o 来定义一个 JS 对象,该对象填充模板中的本地化内容

有一段时间,一切都很顺利。 但是,对我的 JSON 查找的更改导致了错误:"输入行太长"

研究这个错误,我发现 windows shell 对你的行有多长有限制。 不幸的是,我的项目需要整个查找对象。 但是,我开始怀疑 jade 是否可以接受我的查找文件的路径,而不是包含文件内容的字符串。 目前,我正在将内容构建到一个变量中,并用该 ala 调用 jade:

SetLocal EnableDelayedExpansion
set content=
for /F "delims=" %%i in (%sourcedir%'assets'english.json) do set content=!content! %%i
::use the json file as a key for assembling the jade templates 
call jade %sourcedir% --out %destdir% -o"%content%"
EndLocal

如果我可以使用查找文件的路径,那会容易得多。 但是,我不确定如何做到这一点(如果可能的话)。而Jade的文档有点缺乏。

那么,简而言之,Jade是否可以接受JS对象的文件路径而不是包含该对象的字符串? 有没有更好的方法来构造不会超过极限的玉召?

编写一个节点.js脚本,该脚本将读取您的"资产"并调用 jade。像这样:

var fs = require('fs'),
    _ = require('underscore'),
    async = require('async');
var sourceDir = 'path to the directory with your jade templates',
    destinationDir = 'path to the directory where you want the result html files to be contained in';
async.waterfall([
    async.parallel.bind(null, {
        serializedData: fs.readFile.bind(null, 'assets/english.json'),
        files: fs.readDir.bind(null, sourceDir),
    }),
    function (result, callback) {
        var data = JSON.parse(result.serializedData),
            files = result.files;
        async.parallel(_.map(files, function (file) {
            return async.waterfall.bind(null, [
                fs.readFile.bind(null, sourceDir + file),
                function (jadeSource, callback) {
                    process.nextTick(callback.bind(null, jade.compile(jadeSource)(data)));
                },
                fs.writeFile.bind(null, destinationDir + file)
            ]);
        }), callback);
    }
], function (err) {
    if (err) {
        console.log("An error occured: " + err);
    } else {
        console.log("Done!");
    }
});

然后在批处理文件中直接调用此脚本,而不是枚举目录并手动调用 jade。

它不仅可以解决您的问题,还可以更快地工作,因为:

  1. I/O 操作并行完成;
  2. Node.js 在构建过程中只启动一次,而不是像现在这样为每个文件启动它。