Skip to content

Instantly share code, notes, and snippets.

@a-ignatov-parc
Last active September 29, 2016 15:28
Show Gist options
  • Save a-ignatov-parc/0fa860624d95fddc42bcbae6506901ff to your computer and use it in GitHub Desktop.
Save a-ignatov-parc/0fa860624d95fddc42bcbae6506901ff to your computer and use it in GitHub Desktop.
import fs from 'fs';
import stream from 'stream';
import gulp from 'gulp';
import {File} from 'gulp-util';
import rename from 'gulp-rename';
import through from 'through2';
import buffer from 'vinyl-buffer';
gulp.task('task1', function() {
return notesToVinylStream(syncData.create.concat(syncData.update)) // Преобразовываем список статей в стрим виниловых файлов без контента.
.pipe(rename({dirname: NOTES_SRC})) // Указываем путь до реальных файлов
.pipe(read()) // Считываем контент файлов в стримы
.pipe(buffer()) // Так как нам нужно работать с содержимым файлов сразу, то считываем стримы в буферы
.pipe(through.obj(function(file, enc, next) {...})) // Делаем какую-то обработку содержимого файлов
.pipe(gulp.dest(...)); // Записываем результат обработки в файловую систему
}
gulp.task('task2', function() {
return readNotesAsBuffer(syncData.create.concat(syncData.update), NOTES_SRC, '.xml') // Считываем все обрабатываемые статьи в буфер
.pipe(through.obj(function(file, enc, next) {...})) // Делаем какую-то обработку содержимого файлов
.pipe(gulp.dest(...)); // Записываем результат обработки в файловую систему
}
function readNotesAsBuffer(notes, dirname, extname) {
return notesToVinylStream(notes)
.pipe(rename({dirname, extname}))
.pipe(read())
.pipe(buffer());
}
function read() {
return through.obj(function(file, enc, next) {
file.contents = fs.createReadStream(file.path);
this.push(file);
next();
})
}
function notesToVinylStream(list) {
// Создаем стрим
const notesStream = new stream.Readable({objectMode: true});
// Преобразовываем все статьи в виниловые файлы и пушим их в стрим.
list
.map(noteToUrl)
.map(url => new File({contents: null, path: `${url}.xml`}))
.forEach(file => notesStream.push(file));
// Заканчиваем стрим
notesStream.push(null);
// Отдаем стрим на дальнейшую обработку
return notesStream;
}
function noteToUrl({url: [url]}) {
return url;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment