簡體   English   中英

NodeJS&Gulp Streams和Vinyl文件對象 - 用於NPM包的Gulp Wrapper產生不正確的輸出

[英]NodeJS & Gulp Streams & Vinyl File Objects- Gulp Wrapper for NPM package producing incorrect output

目標

我目前正在嘗試為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-Task文件

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"));
});

節點模塊的index.js(Aka,我希望變成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;

資源

你對錯誤的位置是正確的。 修復很簡單。 你只需要解析file.contents ,因為flatten函數在一個對象上操作,而不是在Buffer上。

...
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);
...

如果您計划將來擴展插件,您可能會發現options對象對其他東西很有用。

請隨意查看我寫的一個名為gulp-transform的插件的存儲庫。 我很樂意回答有關它的任何問題。 (例如,如果您願意,我可以為您提供有關實現插件的流模式版本的一些指導)。

更新

我決定接受你的捐款邀請。 你可以在這里查看我的分叉以及我在這里打開的問題。 歡迎您盡可能多地使用,如果您真的喜歡它,我總是可以提交拉取請求。 希望它至少能給你一些想法。

感謝您讓這個項目繼續進行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM