pipe道将Gulpstream文件的内容连接到服务器(connect,express或http)响应

我怀疑这是来自对stream的有限理解,但是我已经到处寻找,并且无法工作。 简而言之,我想要一个Gulpstream,并将stream的串联内容直接传递给一个快速响应, 而无需写入文件系统。

这是我的想法(工作正常):

app.get('*', function(req, res){ var stream = fs.createReadStream(__dirname + '/app/index.html'); stream.pipe(res); }); 

但是我想用一个Gulpstream应用相同的概念:

 app.get('/app/js/concatenated-js-files.js', function(req, res){ gulp.src('app/js/**/*.js') .pipe(concat()) .pipe(res); }); app.listen(5555, function() { console.log('Listening on port 5555'); }); 

从浏览器请求/app/js/concatenated-js-files.js时不起作用并产生以下结果:

 [gulp] Error in plugin 'gulp-concat': Missing fileName option for gulp-concat at module.exports (/Users/lgomez/Projects/index-packager/node_modules/gulp-concat/index.js:10:24) at Object.handle (/Users/lgomez/Projects/index-packager/index.js:83:15) at next_layer (/Users/lgomez/Projects/index-packager/node_modules/express/lib/router/route.js:103:13) at Route.dispatch (/Users/lgomez/Projects/index-packager/node_modules/express/lib/router/route.js:107:5) at /Users/lgomez/Projects/index-packager/node_modules/express/lib/router/index.js:213:24 at Function.proto.process_params (/Users/lgomez/Projects/index-packager/node_modules/express/lib/router/index.js:284:12) at next (/Users/lgomez/Projects/index-packager/node_modules/express/lib/router/index.js:207:19) at Layer.expressInit [as handle] (/Users/lgomez/Projects/index-packager/node_modules/express/lib/middleware/init.js:23:5) at trim_prefix (/Users/lgomez/Projects/index-packager/node_modules/express/lib/router/index.js:255:15) at /Users/lgomez/Projects/index-packager/node_modules/express/lib/router/index.js:216:9 

预计这个错误。 gulp-concat被写入输出到文件。

我想避免写一个与gulp-concat非常相似的gulp插件。 我可以分叉并提出build议,但现在还有另一种方法来实现这一目标吗?

谢谢!

如果您想尝试一下,请使用完整的代码。

 var express = require('express'); var gulp = require('gulp'); var concat = require('gulp-concat'); var app = express(); app.get('/app/js/concatenated-js-files.js', function(req, res){ gulp.src('app/js/**/*.js') .pipe(concat()) .pipe(res); }); app.listen(5555, function() { console.log('Listening on port 5555'); }); // http://localhost:5555/app/js/concatenated-js-files.js 

gulp在虚拟File对象的stream上工作,而不是物理文件。 因此,无论您给予什么名字, gulp-concat都不会写入文件系统。 但是,您仍然会遇到问题,因为您无法直接将这些文件对象发送到res响应。

您需要将虚拟文件的内容写入res 。 一个简单的方法是使用through读取吞吐input并将文件内容写入res 。 如果你的stream处理多个文件,那么你不需要concat

 var through = require('through'); // create a stream that reads gulp File objects and outputs their contents function sendTo(res) { return through( function write(data) { // this will be called once for each file res.write(data.contents); }, function end() { // this will be called when there are no more files res.end() } ); } app.get('/app/js/concatenated-js-files.js', function(req, res){ gulp.src('app/js/**/*.js') .pipe(sendTo(res)); }); 

另外, gulp内部使用vinyl-fs来读取文件,所以如果没有其他的需要,你可以直接使用vinyl-fs。