目标
我目前正在尝试为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;