Here are several approaches you can take to achieve this task:
(1) Utilize the gulp-json-transform
plugin:
var jsonTransform = require('gulp-json-transform');
gulp.task("migratefiles", function () {
return gulp.src("files/**/*.json")
.pipe(jsonTransform(function(json, file) {
var transformedJson = {
"newRootLevel": json
};
return transformedJson;
}))
.pipe(gulp.dest("processed"));
});
Pros:
- Simplicity in usage
- Supports asynchronous processing (if a
Promise
is returned)
- Provides access to the path of each
file
Cons:
- Basic output formatting capabilities only
(2) Employ the gulp-json-editor
plugin:
var jeditor = require('gulp-json-editor');
gulp.task("migratefiles", function () {
return gulp.src("files/**/*.json")
.pipe(jeditor(function(json) {
var transformedJson = {
"newRootLevel": json
};
return transformedJson;
}))
.pipe(gulp.dest("processed"));
});
Pros:
- User-friendly interface
- Detects and matches the indentation used in input files automatically (e.g., two spaces, four spaces, tabs, etc.) for consistent output file formatting
- Offers support for various
js-beautify
options
Cons:
- Seems not to support asynchronous processing
- Lacks a direct way to access the path of each file
(3) Manual approach (directly accessing the vinyl
file object using map-stream
):
var map = require('map-stream');
gulp.task("migratefiles", function () {
return gulp.src("files/**/*.json")
.pipe(map(function(file, done) {
var json = JSON.parse(file.contents.toString());
var transformedJson = {
"newRootLevel": json
};
file.contents = new Buffer(JSON.stringify(transformedJson));
done(null, file);
}))
.pipe(gulp.dest("processed"));
});
Pros:
- Complete control and access over all components
- Supports asynchronous processing with a
done
callback
Cons:
- Might be more challenging to work with