NodeJS&Gulp Streams&乙烯文件对象 – 用于NPM包装的Gulp Wrapper产生不正确的输出
目标
我目前正在尝试为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任务和节点模块的全新开发人员,所以绝对不要让自己的眼睛看起来根本不对。
版本库将是最新的代码,但我也会尽力使问题保持最新。
吞噬任务文件
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(也就是我希望变成一口气)
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;
资源
- https://github.com/gulpjs/gulp/blob/master/docs/writing-a-plugin/README.md
- https://github.com/gulpjs/gulp/blob/master/docs/writing-a-plugin/using-buffers.md
- https://github.com/substack/stream-handbook
你是错的地方。 修复很简单。 你只需要parsingfile.contents
,因为flatten
函数在一个对象上运行,而不是在一个Buffer上运行。
... var flatJSON = new Buffer(JSON.stringify( flatten(JSON.parse(file.contents)))); file.contents = flatJSON; ...
这应该解决你的问题。
既然你是Gulp插件的新手,我希望你不要介意,如果我提出一个build议。 您可能需要考虑为您的用户提供用于美化JSON输出的选项。 要做到这一点,只要让你的主要function接受一个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的插件的存储库。 我很乐意回答关于它的任何问题。 (例如,如果你愿意,我可以给你一些关于实现你的插件的stream模式版本的指导)。
更新
我决定接受你的捐款邀请。 你可以在这里查看我的叉子和我在这里打开的问题。 欢迎您尽可能多地使用,如果您真的喜欢,我总是可以提交一个请求。 希望至less给你一些想法。
感谢您获得这个项目。