0

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

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

研究错误,我发现 Windows shell 对你的行的长度有限制。不幸的是,我的项目需要整个查找对象。但是,我开始想知道翡翠是否可以接受我的查找文件的路径,而不是包含文件内容的字符串。目前,我正在将内容构建到一个变量中并用那个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 对象的文件路径而不是包含该对象的字符串?有没有更好的方法来构建不会超过限制的玉调用?

4

1 回答 1

0

编写一个 node.js 脚本,它将读取您的“资产”并调用玉。就像是:

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 在构建过程中只启动一次,而不是像现在这样为每个文件启动它。
于 2012-08-16T06:56:52.857 回答