• Stars
    star
    1,261
  • Rank 35,744 (Top 0.8 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 10 years ago
  • Updated 11 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Virtual file format.

vinyl

NPM version Downloads Build Status Coveralls Status

Virtual file format.

What is Vinyl?

Vinyl is a very simple metadata object that describes a file. When you think of a file, two attributes come to mind: path and contents. These are the main attributes on a Vinyl object. A file does not necessarily represent something on your computer’s file system. You have files on S3, FTP, Dropbox, Box, CloudThingly.io and other services. Vinyl can be used to describe files from all of these sources.

What is a Vinyl Adapter?

While Vinyl provides a clean way to describe a file, we also need a way to access these files. Each file source needs what I call a "Vinyl adapter". A Vinyl adapter simply exposes a src(globs) and a dest(folder) method. Each return a stream. The src stream produces Vinyl objects, and the dest stream consumes Vinyl objects. Vinyl adapters can expose extra methods that might be specific to their input/output medium, such as the symlink method vinyl-fs provides.

Usage

var Vinyl = require('vinyl');

var jsFile = new Vinyl({
  cwd: '/',
  base: '/test/',
  path: '/test/file.js',
  contents: Buffer.from('var x = 123'),
});

API

new Vinyl([options])

The constructor is used to create a new instance of Vinyl. Each instance represents a separate file, directory or symlink.

All internally managed paths (cwd, base, path, history) are normalized and have trailing separators removed. See Normalization and concatenation for more information.

Options may be passed upon instantiation to create a file with specific properties.

options

Options are not mutated by the constructor.

options.cwd

The current working directory of the file.

Type: String

Default: process.cwd()

options.base

Used for calculating the relative property. This is typically where a glob starts.

Type: String

Default: options.cwd

options.path

The full path to the file.

Type: String

Default: undefined

options.history

Stores the path history. If options.path and options.history are both passed, options.path is appended to options.history. All options.history paths are normalized by the file.path setter.

Type: Array

Default: [] (or [options.path] if options.path is passed)

options.stat

The result of an fs.stat call. This is how you mark the file as a directory or symbolic link. See isDirectory(), isSymbolic() and fs.Stats for more information.

Type: fs.Stats

Default: undefined

options.contents

The contents of the file. If options.contents is a ReadableStream, it is wrapped in a cloneable-readable stream.

Type: ReadableStream, Buffer, or null

Default: null

options.{custom}

Any other option properties will be directly assigned to the new Vinyl object.

var Vinyl = require('vinyl');

var file = new Vinyl({ foo: 'bar' });
file.foo === 'bar'; // true

Instance methods

Each Vinyl object will have instance methods. Every method will be available but may return differently based on what properties were set upon instantiation or modified since.

file.isBuffer()

Returns true if the file contents are a Buffer, otherwise false.

file.isStream()

Returns true if the file contents are a Stream, otherwise false.

file.isNull()

Returns true if the file contents are null, otherwise false.

file.isDirectory()

Returns true if the file represents a directory, otherwise false.

A file is considered a directory when:

  • file.isNull() is true
  • file.stat is an object
  • file.stat.isDirectory() returns true

When constructing a Vinyl object, pass in a valid fs.Stats object via options.stat. If you are mocking the fs.Stats object, you may need to stub the isDirectory() method.

file.isSymbolic()

Returns true if the file represents a symbolic link, otherwise false.

A file is considered symbolic when:

  • file.isNull() is true
  • file.stat is an object
  • file.stat.isSymbolicLink() returns true

When constructing a Vinyl object, pass in a valid fs.Stats object via options.stat. If you are mocking the fs.Stats object, you may need to stub the isSymbolicLink() method.

file.clone([options])

Returns a new Vinyl object with all attributes cloned.

By default custom attributes are cloned deeply.

If options or options.deep is false, custom attributes will not be cloned deeply.

If file.contents is a Buffer and options.contents is false, the Buffer reference will be reused instead of copied.

file.inspect()

Returns a formatted-string interpretation of the Vinyl object. Automatically called by node's console.log.

Instance properties

Each Vinyl object will have instance properties. Some may be unavailable based on what properties were set upon instantiation or modified since.

file.contents

Gets and sets the contents of the file. If set to a ReadableStream, it is wrapped in a cloneable-readable stream.

Throws when set to any value other than a ReadableStream, a Buffer or null.

Type: ReadableStream, Buffer, or null

file.cwd

Gets and sets current working directory. Will always be normalized and have trailing separators removed.

Throws when set to any value other than non-empty strings.

Type: String

file.base

Gets and sets base directory. Used for relative pathing (typically where a glob starts). When null or undefined, it simply proxies the file.cwd property. Will always be normalized and have trailing separators removed.

Throws when set to any value other than non-empty strings or null/undefined.

Type: String

file.path

Gets and sets the absolute pathname string or undefined. Setting to a different value appends the new path to file.history. If set to the same value as the current path, it is ignored. All new values are normalized and have trailing separators removed.

Throws when set to any value other than a string.

Type: String

file.history

Array of file.path values the Vinyl object has had, from file.history[0] (original) through file.history[file.history.length - 1] (current). file.history and its elements should normally be treated as read-only and only altered indirectly by setting file.path.

Type: Array

file.relative

Gets the result of path.relative(file.base, file.path).

Throws when set or when file.path is not set.

Type: String

Example:

var file = new File({
  cwd: '/',
  base: '/test/',
  path: '/test/file.js',
});

console.log(file.relative); // file.js

file.dirname

Gets and sets the dirname of file.path. Will always be normalized and have trailing separators removed.

Throws when file.path is not set.

Type: String

Example:

var file = new File({
  cwd: '/',
  base: '/test/',
  path: '/test/file.js',
});

console.log(file.dirname); // /test

file.dirname = '/specs';

console.log(file.dirname); // /specs
console.log(file.path); // /specs/file.js

file.basename

Gets and sets the basename of file.path.

Throws when file.path is not set.

Type: String

Example:

var file = new File({
  cwd: '/',
  base: '/test/',
  path: '/test/file.js',
});

console.log(file.basename); // file.js

file.basename = 'file.txt';

console.log(file.basename); // file.txt
console.log(file.path); // /test/file.txt

file.stem

Gets and sets stem (filename without suffix) of file.path.

Throws when file.path is not set.

Type: String

Example:

var file = new File({
  cwd: '/',
  base: '/test/',
  path: '/test/file.js',
});

console.log(file.stem); // file

file.stem = 'foo';

console.log(file.stem); // foo
console.log(file.path); // /test/foo.js

file.extname

Gets and sets extname of file.path.

Throws when file.path is not set.

Type: String

Example:

var file = new File({
  cwd: '/',
  base: '/test/',
  path: '/test/file.js',
});

console.log(file.extname); // .js

file.extname = '.txt';

console.log(file.extname); // .txt
console.log(file.path); // /test/file.txt

file.symlink

Gets and sets the path where the file points to if it's a symbolic link. Will always be normalized and have trailing separators removed.

Throws when set to any value other than a string.

Type: String

Vinyl.isVinyl(file)

Static method used for checking if an object is a Vinyl file. Use this method instead of instanceof.

Takes an object and returns true if it is a Vinyl file, otherwise returns false.

Note: This method uses an internal flag that some older versions of Vinyl didn't expose.

Example:

var Vinyl = require('vinyl');

var file = new Vinyl();
var notAFile = {};

Vinyl.isVinyl(file); // true
Vinyl.isVinyl(notAFile); // false

Vinyl.isCustomProp(property)

Static method used by Vinyl when setting values inside the constructor or when copying properties in file.clone().

Takes a string property and returns true if the property is not used internally, otherwise returns false.

This method is useful for inheritting from the Vinyl constructor. Read more in Extending Vinyl.

Example:

var Vinyl = require('vinyl');

Vinyl.isCustomProp('sourceMap'); // true
Vinyl.isCustomProp('path'); // false -> internal getter/setter

Normalization and concatenation

Since all properties are normalized in their setters, you can just concatenate with /, and normalization takes care of it properly on all platforms.

Example:

var file = new File();
file.path = '/' + 'test' + '/' + 'foo.bar';

console.log(file.path);
// posix => /test/foo.bar
// win32 => \\test\\foo.bar

But never concatenate with \, since that is a valid filename character on posix system.

Extending Vinyl

When extending Vinyl into your own class with extra features, you need to think about a few things.

When you have your own properties that are managed internally, you need to extend the static isCustomProp method to return false when one of these properties is queried.

var Vinyl = require('vinyl');

var builtInProps = ['foo', '_foo'];

class SuperFile extends Vinyl {
  constructor(options) {
    super(options);
    this._foo = 'example internal read-only value';
  }

  get foo() {
    return this._foo;
  }

  static isCustomProp(name) {
    return super.isCustomProp(name) && builtInProps.indexOf(name) === -1;
  }
}

// `foo` won't be assigned to the object below
new SuperFile({ foo: 'something' });

This makes properties foo and _foo skipped when passed in options to constructor(options) so they don't get assigned to the new object and override your custom implementation. They also won't be copied when cloning. Note: The _foo and foo properties will still exist on the created/cloned object because you are assigning _foo in the constructor and foo is defined on the prototype.

Same goes for clone(). If you have your own internal stuff that needs special handling during cloning, you should extend it to do so.

License

MIT

More Repositories

1

gulp

A toolkit to automate & enhance your workflow
JavaScript
32,856
star
2

vinyl-fs

Vinyl adapter for the file system.
JavaScript
963
star
3

liftoff

Launch your command line tool with ease.
JavaScript
836
star
4

gulp-util

[deprecated] - See https://medium.com/gulpjs/gulp-util-ca3b1f9f9ac5
JavaScript
830
star
5

gulp-cli

Command Line Interface for gulp.
JavaScript
392
star
6

plugins

[Unused] Very old plugin search website
JavaScript
280
star
7

interpret

A dictionary of file extensions and associated module loaders.
JavaScript
254
star
8

undertaker

Task registry that allows composition through series/parallel methods.
JavaScript
194
star
9

glob-stream

Readable streamx interface over anymatch.
JavaScript
178
star
10

bach

Compose your async functions with elegance.
JavaScript
132
star
11

fancy-log

Log things, prefixed with a timestamp.
JavaScript
119
star
12

findup-sync

Find the first file matching a given pattern in the current directory or the nearest ancestor directory.
JavaScript
97
star
13

glob-watcher

Watch globs and execute a function upon change, with intelligent defaults for debouncing and queueing.
JavaScript
79
star
14

glob-parent

Extract the non-magic parent path from a glob string.
JavaScript
76
star
15

async-done

Allows libraries to handle various caller provided asynchronous functions uniformly. Maps promises, observables, child processes and streams, and callbacks to callback style.
JavaScript
69
star
16

v8flags

Get available v8 and Node.js flags.
JavaScript
56
star
17

gulplog

Logger for gulp and gulp plugins
JavaScript
56
star
18

rechoir

Prepare a node environment to require files with different extensions.
JavaScript
47
star
19

replace-ext

Replaces a file extension with another one.
JavaScript
46
star
20

gulpjs.github.io

The gulp website
JavaScript
45
star
21

ordered-read-streams

Combines array of streams into one Readable stream in strict order.
JavaScript
28
star
22

now-and-later

Map over an array or object of values in parallel or series, passing each through the async iterator, with optional lifecycle hooks.
JavaScript
24
star
23

hacker

Hack on your project easily. A liftoff proof-of-concept.
JavaScript
23
star
24

flagged-respawn

A tool for respawning node binaries when special flags are present.
JavaScript
21
star
25

artwork

Artwork for the gulp project
21
star
26

plugin-error

Error handling for vinyl plugins. Just an abstraction of what's in gulp-util with minor reformatting.
JavaScript
21
star
27

empty-dir

Check if a directory is empty.
JavaScript
20
star
28

sparkles

Namespaced global event emitter
JavaScript
20
star
29

acceptance

Acceptance test suite for plugins
19
star
30

undertaker-forward-reference

Undertaker custom registry supporting forward referenced tasks.
JavaScript
19
star
31

glogg

Global logging utility.
JavaScript
18
star
32

lead

Sink your streams.
JavaScript
17
star
33

undertaker-registry

Default registry in gulp 4.
JavaScript
17
star
34

vinyl-sourcemap

Add/write sourcemaps to/from Vinyl files.
JavaScript
15
star
35

last-run

Capture and retrieve the last time a function was run
JavaScript
14
star
36

path-dirname

Node.js path.dirname() ponyfill
JavaScript
13
star
37

fined

Find a file given a declaration of locations.
JavaScript
12
star
38

async-settle

Settle an async function. It will always complete successfully with an object of the resulting state.
JavaScript
11
star
39

value-or-function

Normalize a value or function, applying extra args to the function
JavaScript
11
star
40

copy-props

Copy properties deeply between two objects
JavaScript
10
star
41

to-through

Wrap a Readable stream in a Transform stream.
JavaScript
10
star
42

semver-greatest-satisfied-range

Find the greatest satisfied semver range from an array of ranges.
JavaScript
9
star
43

mute-stdout

Mute and unmute stdout
JavaScript
9
star
44

resolve-options

Resolve an options object based on configuration.
JavaScript
9
star
45

has-gulplog

Check if gulplog is available before attempting to use it
JavaScript
9
star
46

clone-buffer

Easier Buffer cloning in node.
JavaScript
9
star
47

eslint-config-gulp

Sharable eslint config for gulp projects
JavaScript
8
star
48

async-once

Guarantee a node-style async function is only executed once.
JavaScript
8
star
49

fs-mkdirp-stream

Ensure directories exist before writing to them.
JavaScript
8
star
50

undertaker-common-tasks

Proof-of-concept custom registry that pre-defines tasks.
JavaScript
7
star
51

remove-bom-stream

Remove a UTF8 BOM at the start of the stream.
JavaScript
7
star
52

registry

[Unused] NPM on ElasticSearch
JavaScript
5
star
53

better-stats

A replacement for node's fs.Stats with more utility
JavaScript
5
star
54

theming-log

Creates a logger with theme for text decoration.
JavaScript
4
star
55

undertaker-task-metadata

Proof-of-concept custom registry that attaches metadata to each task.
JavaScript
4
star
56

vinyl-contents

Utility to read the contents of a vinyl file.
JavaScript
4
star
57

replace-homedir

Replace user home in a string with another string. Useful for tildifying a path.
JavaScript
4
star
58

each-props

Process object properties deeply.
JavaScript
3
star
59

evented-require

Require modules and receive events.
JavaScript
3
star
60

update-template

Updates a gulpjs repository to match our current scaffold.
JavaScript
3
star
61

.github

GitHub template files for the gulpjs organization.
3
star
62

vinyl-prepare

[deprecated] This module's API was never satisfactory and isn't used in gulp - please don't use.
JavaScript
3
star
63

.boilerplate

The boilerplate template for gulp packages.
3
star
64

parse-node-version

Turn node's process.version into something useful.
JavaScript
2
star
65

default-resolution

Get the default resolution time based on the current node version, optionally overridable
JavaScript
2
star
66

jscs-preset-gulp

Sharable jscs config for gulp projects
2
star
67

conventional-changelog-gulp

conventional-changelog gulp preset
JavaScript
1
star
68

emit-mapper

Re-emit events while mapping them to new names.
JavaScript
1
star