node.js 如何从 Gulp 中的字符串创建文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23230569/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do you create a file from a string in Gulp?
提问by Daryl
In my gulpfile I have a version number in a string. I'd like to write the version number to a file. Is there a nice way to do this in Gulp, or should I be looking at more general NodeJS APIs?
在我的 gulpfile 中,我有一个字符串版本号。我想将版本号写入文件。在 Gulp 中是否有一种很好的方法可以做到这一点,还是应该查看更通用的 NodeJS API?
采纳答案by Christoph Neumann
If you'd like to do this in a gulp-like way, you can create a stream of "fake" vinyl files and call pipeper usual. Here's a function for creating the stream. "stream" is a core module, so you don't need to install anything:
如果您想以类似吞咽的方式执行此操作,您可以创建一个“假”乙烯基文件流并按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
}
You can use it like this:
你可以这样使用它:
gulp.task('version', function () {
var pkg = require('package.json')
return string_src("version", pkg.version)
.pipe(gulp.dest('build/'))
})
回答by fregante
It's pretty much a one-liner in node:
它几乎是 node 中的一个单行:
require('fs').writeFileSync('dist/version.txt', '1.2.3');
Or from package.json:
或者从 package.json:
var pkg = require('./package.json');
var fs = require('fs');
fs.writeFileSync('dist/version.txt', 'Version: ' + pkg.version);
I'm using it to specify a build date in an easily-accessible file, so I use this code before the usual return gulp.src(...)in the buildtask:
我使用它在易于访问的文件中指定构建日期,因此我return gulp.src(...)在build任务中的通常使用之前使用此代码:
require('fs').writeFileSync('dist/build-date.txt', new Date());
回答by mjhasbach
This can also be done with vinyl-source-stream. See this documentin the gulp repository.
这也可以通过vinyl-source-stream来完成。请参阅gulp 存储库中的此文档。
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'));
});
回答by GOTO 0
According to the maintainer of Gulp, the preferred way to write a string to a file is using fs.writeFilewith the task callback.
根据 Gulp 的维护者的说法,将字符串写入文件的首选方法是使用fs.writeFile任务回调。
var fs = require('fs');
var gulp = require('gulp');
gulp.task('taskname', function(cb){
fs.writeFile('filename.txt', 'contents', cb);
});
Source: https://github.com/gulpjs/gulp/issues/332#issuecomment-36970935
来源:https: //github.com/gulpjs/gulp/issues/332#issuecomment-36970935
回答by Dave James Miller
You can also use gulp-file:
您还可以使用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/'))
});
or without using gulp.src():
或不使用gulp.src():
gulp.task('version', function () {
var pkg = require('package.json')
return file('version', pkg.version, {src: true})
.pipe(gulp.dest('build/'))
});
回答by Mike Causer
The gulp-headerpackage can be used to prefix files with header banners.
该一饮而尽头包可以使用头横幅前缀的文件。
eg. This will inject a banner into the header of your javascript files.
例如。这将在您的 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 is a streaming build system leveraging pipes.
Gulp 是一个利用管道的流式构建系统。
If you simply want to write a new file with an arbitrary string, you can use built in node fsobject.
如果您只是想用任意字符串编写一个新文件,您可以使用内置的节点 fs对象。
回答by Jonas Berlin
Using the string-to-streamand vinyl-source-streammodules:
使用string-to-stream和vinyl-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'));
回答by William Bernting
Here's an answer that works in 2019.
这是一个在 2019 年有效的答案。
Plugin:
插入:
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);
}
And in your gulp pipeline:
在你的 gulp 管道中:
gulp.src([
...
])
.pipe(stringSrc('version.json', '123'))
.pipe(gulp.dest(destinationPath))
From source: https://github.com/gulpjs/gulp/tree/master/docs/writing-a-plugin#modifying-file-content
来源:https: //github.com/gulpjs/gulp/tree/master/docs/writing-a-plugin#modifying-file-content
The function parameter that you pass to through.obj() is a _transform function which will operate on the input file. You may also provide an optional _flush function if you need to emit a bit more data at the end of the stream.
From within your transform function call this.push(file) 0 or more times to pass along transformed/cloned files. You don't need to call this.push(file) if you provide all output to the callback() function.
Call the callback function only when the current file (stream/buffer) is completely consumed. If an error is encountered, pass it as the first argument to the callback, otherwise set it to null. If you have passed all output data to this.push() you can omit the second argument to the callback.
Generally, a gulp plugin would update file.contents and then choose to either:
call callback(null, file) or make one call to this.push(file)
您传递给 through.obj() 的函数参数是一个 _transform 函数,它将对输入文件进行操作。如果您需要在流的末尾发出更多数据,您还可以提供一个可选的 _flush 函数。
从您的转换函数中调用 this.push(file) 0 次或更多次以传递转换/克隆的文件。如果您将所有输出提供给 callback() 函数,则不需要调用 this.push(file)。
仅在当前文件(流/缓冲区)被完全消耗时调用回调函数。如果遇到错误,将其作为第一个参数传递给回调,否则将其设置为 null。如果您已将所有输出数据传递给 this.push(),您可以省略回调的第二个参数。
通常,gulp 插件会更新 file.contents 然后选择:
调用 callback(null, file) 或调用 this.push(file)
回答by Vikram
This can also be achieved using gulp-tap
这也可以使用gulp-tap来实现
This can be especially helpful if you have identified multiple files that require this header. Here is relevant code (Also from gulp-tap documentation)
如果您确定了多个需要此标头的文件,这将特别有用。这是相关代码(也来自 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');

