如何与node.jsstream中的<File>对象进行交互?

我正在使用gulp来构build一个glob匹配的文件stream,并将它们的嵌套结构全部移动到一个新的位置。 要做到这一点,我首先想build立一个简单的“通过”stream,看看我通过从gulp.src()pipe道通过。

这是我的testinggulpfile.js:

var through = require("through"); var fs = require("fs"); function write(file) { console.log(file); console.log(file.toString()); } gulp.task("move", function () { return gulp.src("./**") .pipe(through(write)); }); 

如果我在命令行上运行gulp'move'任务,我得到的输出如下所示:

 <File "some/path"> [object Object] <File "some/path/file.js" <Buffer 2f 2a 0a 0a 4f 72 67 69 6e 61 6c 20 53 74 79 6c 65 20 66 72 6f 6d 20 65 74 68 61 6e 73 63 68 6f 6f 6e 6f 76 65 72 2e 63 6f 6d 2f 73 6f 6c 61 72 69 7a 65 ...>> [object Object] 

那些东西是什么? 我怎样才能与他们互动?

那些是乙烯基物体。 它们是通过gulpstream传递的核心数据types。 包含有关文件的信息(如path信息和内容作为缓冲区或stream)。 您可以使用gulp-debug更好地查看数据。

如果你想移动一堆文件,同时保留它们的相对path,你可以执行以下操作之一,不需要自己深入代码:

 gulp.src('/a/single/src/path/**/*.foo').pipe(gulp.dest('/a/single/dest/path')); 

或者,如果你有一堆不同的球体:

 gulp.src(['/a/src/path/foo/**/*.foo', '/a/src/path/bar/**/*.bar'], {base: '/a/src/path/'}) .pipe(gulp.dest('/a/dest/path/')); 

大多数情况下,您将使用gulp插件来操作文件,然后将结果传递给gulp.dest() ,而不是自己操纵它们。

如果你需要操作这些文件,有几个插件可以帮助你:

  • gulp-tap允许你进入stream的峰值,并可以select修改文件或缓冲区。
  • 乙烯地图让你轻松修改文件的内容
  • gulp-filter可以帮助你过滤stream如果globbing不起作用。

你可以使用这个js查看文件属性:

 var propValue; for(var propName in file) { propValue = file[propName]; console.log('name:' + propName, ', value:<<<',propValue,'>>>'); } Sample Output name:history , value:"C:\Temp\test.txt" name:cwd , value:"C:\Temp" name:base , value:"C:\Temp" name:_contents , value: full file contents name:isBuffer , value:"function () { name:isStream , value:"function () { name:isNull , value:"function () { name:isDirectory , value:"function () { name:clone , value:"function (opt) { name:pipe , value:"function (stream, opt) { name:inspect , value:"function () { name:stat , value:<<< { dev: 0, mode: 33206, nlink: 1, uid: 0, gid: 0, rdev: 0, ino: 0, size: 874, atime: Sat Sep 19 2015 14:34:51 GMT+1000 (AUS Eastern Standard Time), mtime: Sat Sep 19 2015 14:34:51 GMT+1000 (AUS Eastern Standard Time), ctime: Sat Sep 12 2015 14:59:40 GMT+1000 (AUS Eastern Standard Time) } >>> Usage: console.log('file name:', file.relative); console.log('file current working directory:', file.cwd); console.log('file isDirectory:', file.isDirectory());