如何在Gulp中从字符串创建文件?

时间:2014-04-22 21:29:32

标签: node.js gulp

在我的gulpfile中,我在字符串中有一个版本号。我想将版本号写入文件。在Gulp中有一个很好的方法吗,或者我应该关注更一般的NodeJS API?

9 个答案:

答案 0 :(得分:66)

它几乎是节点中的单行:

require('fs').writeFileSync('dist/version.txt', '1.2.3');

或者来自package.json:

var pkg = require('./package.json');
var fs = require('fs');
fs.writeFileSync('dist/version.txt', 'Version: ' + pkg.version);

我使用它在易于访问的文件中指定构建日期,因此我在return gulp.src(...)任务中的常规build之前使用此代码:

require('fs').writeFileSync('dist/build-date.txt', new Date());

答案 1 :(得分:65)

如果您想以类似gulp的方式执行此操作,则可以创建“假”乙烯基文件流并按常规调用pipe。这是创建流的功能。 “stream”是一个核心模块,因此您无需安装任何内容:

function string_src(filename, string) {
  var src = require('stream').Readable({ objectMode: true })
  src._read = function () {
    this.push(new gutil.File({
      cwd: "",
      base: "",
      path: filename,
      contents: new Buffer(string)
    }))
    this.push(null)
  }
  return src
}

你可以像这样使用它:

gulp.task('version', function () {
  var pkg = require('package.json')
  return string_src("version", pkg.version)
    .pipe(gulp.dest('build/'))
})

答案 2 :(得分:27)

这也可以使用vinyl-source-stream完成。请参阅gulp存储库中的this document

var gulp = require('gulp'),
    source = require('vinyl-source-stream');

gulp.task('some-task', function() {
    var stream = source('file.txt');

    stream.end('some data');
    stream.pipe(gulp.dest('output'));
});

答案 3 :(得分:17)

根据Gulp的维护者的说法,将字符串写入文件的首选方法是使用fs.writeFile和任务回调。

var btns = document.querySelectorAll('a.copy_btn');
var clipboard = new Clipboard(btns);

clipboard.on('success', function (e) {
    console.log(e);
});
clipboard.on('error', function (e) {
    console.log(e);
});

来源:https://github.com/gulpjs/gulp/issues/332#issuecomment-36970935

答案 4 :(得分:13)

您还可以使用gulp-file

var gulp = require('gulp');
var file = require('gulp-file');

gulp.task('version', function () {
    var pkg = require('package.json')

    return gulp.src('src/**')
        .pipe(file('version', pkg.version))
        .pipe(gulp.dest('build/'))
});

或不使用gulp.src()

gulp.task('version', function () {
    var pkg = require('package.json')

    return file('version', pkg.version, {src: true})
        .pipe(gulp.dest('build/'))
});

答案 5 :(得分:5)

gulp-header包可用于为带有标题横幅的文件添加前缀。

例如。这会在你的javascript文件的标题中注入一个横幅。

var header = require('gulp-header');
var pkg = require('./package.json');
var banner = ['/**',
  ' * <%= pkg.name %> - <%= pkg.description %>',
  ' * @version v<%= pkg.version %>',
  ' * @link <%= pkg.homepage %>',
  ' * @license <%= pkg.license %>',
  ' */',
  ''].join('\n');

gulp.src('./foo/*.js')
  .pipe(header(banner, { pkg: pkg } ))
  .pipe(gulp.dest('./dist/')

Gulp是一个利用管道的流式构建系统。

如果您只想编写带有任意字符串的新文件,则可以使用内置的node fs对象。

答案 6 :(得分:2)

使用string-to-streamvinyl-source-stream模块:

var str = require('string-to-stream');
var source = require('vinyl-source-stream');
var gulp = require('gulp');

str('1.4.27').pipe(source('version.txt')).pipe(gulp.dest('dist'));

答案 7 :(得分:1)

这也可以使用gulp-tap

来实现

如果您已识别出需要此标头的多个文件,则此功能尤其有用。这是相关代码(也来自gulp-tap文档)

var gulp = require('gulp'),
    tap = require('gulp-tap');

gulp.src("src/**")
    .pipe(tap(function(file){
           file.contents = Buffer.concat([
             new Buffer('Some Version Header', 'utf8'),
             file.contents
           ]);
         }))
    .pipe(gulp.dest('dist');

答案 8 :(得分:0)

以下是在2019年有效的答案。

插件:

var Vinyl = require('vinyl');
var through = require('through2');
var path = require('path');

// https://github.com/gulpjs/gulp/tree/master/docs/writing-a-plugin#modifying-file-content
function stringSrc(filename, string) {
    /**
     * @this {Transform}
     */
    var transform = function(file, encoding, callback) {
        if (path.basename(file.relative) === 'package.json') {
            file.contents = Buffer.from(
                JSON.stringify({
                    name: 'modified-package',
                    version: '1.0.0',
                }),
            );
        }

        // if you want to create multiple files, use this.push and provide empty callback() call instead
        // this.push(file);
        // callback();

        callback(null, file);
    };

    return through.obj(transform);
}

在您的吞咽管道中:

gulp.src([
    ...
])
.pipe(stringSrc('version.json', '123'))
.pipe(gulp.dest(destinationPath))

来源:https://github.com/gulpjs/gulp/tree/master/docs/writing-a-plugin#modifying-file-content

  

您通过through.obj()传递的函数参数是_transform   函数将对输入文件起作用。您也可以提供   可选的_flush函数,如果您需要在   流的结尾。

     

从您的转换函数中调用this.push(file)0或更大   时间传递经过转换/克隆的文件。你不需要打电话   如果将所有输出提供给callback()函数,则为this.push(file)。

     

仅在当前文件(流/缓冲区)时调用回调函数   被完全消耗掉。如果遇到错误,请将其作为   回调的第一个参数,否则将其设置为null。如果你有   将所有输出数据传递给this.push()您可以省略第二个参数   到回调。

     

通常,gulp插件会更新file.contents,然后选择   要么:

     

调用回调(null,文件)或一次调用this.push(文件)

相关问题