6

目标

我目前正在尝试为NPM Flat编写一个 Gulp 包装器,可以轻松地在 Gulp 任务中使用。我觉得这对 Node 社区很有用,也可以实现我的目标。该存储库供每个人查看、贡献、使用和拉取请求。我正在尝试制作多个 JSON 文件的扁平化(使用点表示法)副本。然后我想将它们复制到同一个文件夹中,只需将文件扩展名修改为从 *.json 到 *.flat.json。

我的问题

我在 JSON 文件中得到的结果看起来像乙烯基文件或字节码。例如,我希望输出像 "views.login.usernamepassword.login.text": "Login",但我得到类似{"0":123,"1":13,"2":10,"3":9,"4":34,"5":100,"6":105 ...等的东西

我的方法

我是开发 Gulp 任务和节点模块的新手,所以一定要留意根本错误的事情。

存储库将是最新的代码,但我也会尝试使问题与它保持同步。

Gulp 任务文件

var gulp = require('gulp'),
    plugins = require('gulp-load-plugins')({camelize: true});
var gulpFlat = require('gulp-flat');
var gulpRename = require('gulp-rename');
var flatten = require('flat');

gulp.task('language:file:flatten', function () {

return gulp.src(gulp.files.lang_file_src)
    .pipe(gulpFlat())
    .pipe(gulpRename( function (path){
        path.extname = '.flat.json'
    }))
    .pipe(gulp.dest("App/Languages"));
});

Node 模块的 index.js(也就是我希望变成 gulp-flat)

var through = require('through2');
var gutil = require('gulp-util');
var flatten = require('flat');
var PluginError = gutil.PluginError;

// consts
const PLUGIN_NAME = 'gulp-flat';


// plugin level function (dealing with files)
function flattenGulp() {

    // creating a stream through which each file will pass
    var stream = through.obj(function(file, enc, cb) {
        if (file.isBuffer()) {

             //FIXME: I believe this is the problem line!!
            var flatJSON = new Buffer(JSON.stringify(
                flatten(file.contents)));
            file.contents = flatJSON;
    }

    if (file.isStream()) {

        this.emit('error', new PluginError(PLUGIN_NAME, 'Streams not supported! NYI'));
        return cb();
    }

    // make sure the file goes through the next gulp plugin
    this.push(file);
    // tell the stream engine that we are done with this file
    cb();
});

// returning the file stream
return stream;
}

// exporting the plugin main function
module.exports = flattenGulp;

资源

4

1 回答 1

1

你是正确的错误在哪里。修复很简单。您只需要解析file.contents,因为该flatten函数对对象而不是缓冲区进行操作。

...
var flatJSON = new Buffer(JSON.stringify(
  flatten(JSON.parse(file.contents))));
file.contents = flatJSON;
...

那应该可以解决您的问题。

而且由于您是 Gulp 插件的新手,我希望您不介意我提出建议。您可能需要考虑为您的用户提供美化 JSON 输出的选项。为此,只需让您的 main 函数接受一个options对象,然后您可以执行以下操作:

...
var flatJson = flatten(JSON.parse(file.contents));
var jsonString = JSON.stringify(flatJson, null, options.pretty ? 2 : null);
file.contents = new Buffer(jsonString);
...

如果您计划将来扩展您的插件,您可能会发现选项对象对其他事情很有用。

随意查看我编写的名为gulp-transform的插件的存储库。我很乐意回答有关它的任何问题。(例如,如果您愿意,我可以为您提供一些关于实现插件的流模式版本的指导)。

更新

我决定接受你的捐款邀请。你可以在这里查看我的 fork和我在这里打开的问题。欢迎您随心所欲地使用,如果您真的喜欢它,我可以随时提交拉取请求。希望它至少能给你一些想法。

感谢您让这个项目顺利进行。

于 2016-02-22T23:33:47.007 回答