我目前正在尝试为 NPM Flat 编写一个 Gulp 包装器可以很容易地在 Gulp 任务中使用。我觉得这对 Node 社区很有用,也可以实现我的目标。 <强> The repository is here for everyone to view , contribute to, play with and pull request. 我正在尝试制作多个 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 任务和 Node 模块的新手,所以一定要留意根本性的错误。
存储库将是最新的代码,但我也会尽量使问题与它保持同步。
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;
最佳答案
你说的对,错误在哪里。修复很简单。您只需要解析 file.contents,因为 flatten 函数在 object 上运行,而不是在 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);
...
如果您计划在未来扩展您的插件,您可能会发现选项对象对其他事情很有用。
请随意查看我编写的名为 gulp-transform 的插件的存储库。 .我很乐意回答有关它的任何问题。 (例如,如果您愿意,我可以为您提供一些有关实现插件流模式版本的指导)。
我决定接受你的贡献邀请。你可以查看我的fork here我打开的问题here .欢迎您随意使用,如果您真的喜欢它,我可以随时提交拉取请求。希望它至少能给您一些想法。
感谢您让这个项目继续进行。
关于javascript - NodeJS & Gulp Streams & Vinyl File Objects - Gulp Wrapper for NPM package producing incorrect output,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35564976/