May 25, 2021 Grunt
There are many ways to read and write files, traverse the file system, and find files through pattern matching. Many of these methods are encapsulated .js functions in The Node, but provide additional error handling, logging, and character encoding conversion.
Note: All file paths refer
Gruntfile
file unless the current working directory is changed by the
grunt.file.setBase
--base
on the command line.
Setting this property changes the
grunt.file
methods. T
he default
'utf8'
If you must change this value, it is recommended that you change it as early as possible in the Gruntfile file.
grunt.file.defaultEncoding = 'utf8';
Added to version 0.4.2
Whether to keep the byte order marker (BOM) at
file.read
grunt.file.preserveBOM = false;
Read and return the contents of the file.
The return value is a string, and
options.encoding
null
a Buffer is
returned.
grunt.file.read(filepath [, options])
options
can set the following properties:
var options = {
// If an encoding is not specified, default to grunt.file.defaultEncoding.
// If specified as null, returns a non-decoded Buffer instead of a string.
encoding: encodingName
};
Read the contents of a file, parse it in JSON format, and return the results.
See
grunt.file.read
list of the parameters it supports.
grunt.file.readJSON(filepath [, options])
Read the contents of a file, parse it in YAML format, and return the results.
See
grunt.file.read
list of the parameters it supports.
grunt.file.readYAML(filepath [, options])
The specified content is written to the file and, if necessary, all directories that do not exist in the file path are created. Strings are encoded according to the specified character encoding, and Buffers is written to disk in the specified way.
If you specify the
--no-write
line parameter, the file will not actually be written.
grunt.file.write(filepath, contents [, options])
options
can set the following properties:
var options = {
// If an encoding is not specified, default to grunt.file.defaultEncoding.
// If `contents` is a Buffer, encoding is ignored.
encoding: encodingName
};
Copy the original file to the specified path and, if necessary, create all directories that do not exist in the file path
If you specify the
--no-write
line parameter, the file will not actually be written.
grunt.file.copy(srcpath, destpath [, options])
options
can set the following properties:
var options = {
// If an encoding is not specified, default to grunt.file.defaultEncoding.
// If null, the `process` function will receive a Buffer instead of String.
encoding: encodingName,
// The source file contents, source file path, and destination file path
// are passed into this function, whose return value will be used as the
// destination file's contents. If this function returns `false`, the file
// copy will be aborted.
process: processFunction,
// These optional globbing patterns will be matched against the filepath
// (not the filename) using grunt.file.isMatch. If any specified globbing
// pattern matches, the file won't be processed via the `process` function.
// If `true` is specified, processing will be prevented.
noProcess: globbingPatterns
};
Delete the specified file. Files and directories are recursively deleted in turn.
Will not delete the current working directory or files outside the current working directory unless the
--force
command-line option is specified.
If the
--no-write
is specified, the file path will not actually be deleted.
grunt.file.delete(filepath [, options])
options
can only set the following properties:
var options = {
// Enable deleting outside the current working directory. This option may
// be overridden by the --force command-line option.
force: true
};
Works like
mkdir -p
C
reate a directory and all intermediate directories.
If
mode
specified, the default is
0777 & (~process.umask())
.
Without
--no-write
line argument, the directory is not actually created.
grunt.file.mkdir(dirpath [, mode])
Recursively traverses the entire directory, executing the
callback
each file.
grunt.file.recurse(rootdir, callback)
The callback function receives the following parameters:
function callback(abspath, rootdir, subdir, filename) {
// The full path to the current file, which is nothing more than
// the rootdir + subdir + filename arguments, joined.
abspath
// The root director, as originally specified.
rootdir
// The current file's directory, relative to rootdir.
subdir
// The filename of the current file, without any directory parts.
filename
}
Sometimes it is unrealistic to specify all the original file paths separately, so Grunt supports the file name expansion (or globbing) through the built-in node-glob library.
See the "Globbing patterns" section of the Configuration Tasks guide for examples of globbing patterns.
Returns a special array of files or directory paths that match a given wildcard pattern. T
his method receives a match pattern or an array of matching patterns split by a comma. I
f the path matches the pattern
!
A
t the beginning, it excludes matching items from the returned array.
Patterns are processed in the specified order, so it is important to include and exclude the order of files.
grunt.file.expand([options, ] patterns)
File paths are
Gruntfile
files unless the current working directory is modified by
grunt.file.setBase
or
--base
command line parameters.
options
objects support
all minimatch library
parameters, as well as additional ones, as follows:
filter
E
accepts a valid
fs.
The Stats method name,
or a function that
src
file path match,
true
or
false
nonull
the
src
pattern even if the file match fails.
Combined with
-verbose
this option facilitates debugging of file path issues.
matchBase
pattern without slashes only matches the basic name section.
For example, this
*.js
the
**/*.js
the same.
cwd
the pattern relative to the current path, and all returned file paths are relative to the current path.
Returns an
src-dest
file mapping objects. E
ach source file is matched by the pattern specified, and then the matching file path is
dest
the specified dest (the dest holds the matching file path). T
his file path is processed or renamed according to the specified options.
Check
grunt.file.expand
documentation to learn how to specify
patterns
options
grunt.file.expandMapping(patterns, dest [, options])
Note: This method can be used to programmatically generate an array
files
using the syntax described in the "Dynamic build file objects" section of the Configuration Tasks guide.
In addition to supporting
grunt.file.expand
options
also support these properties:
var options = {
// The directory from which patterns are matched. Any string specified as
// cwd is effectively stripped from the beginning of all matched paths.
cwd: String,
// Remove the path component from all matched src files. The src file path
// is still joined to the specified dest.
flatten: Boolean,
// Remove anything after (and including) either the first or last "." in the
// destination path (indicated by options.extDot), then append this value.
ext: String,
// *Added in 0.4.3*
// Indicates where the period demarcating the extension is located. Can take:
// - 'first' (extension begins after the first period in the file name)
// - 'last' (extension begins after the last period)
// Default: 'first'
extDot: String,
// If specified, this function will be responsible for returning the final
// dest filepath. By default, it joins dest and matchedSrcPath like so:
rename: function(dest, matchedSrcPath, options) {
return path.join(dest, matchedSrcPath);
}
};
Match one or more match patterns for one or more file paths. R
eturns a special array that contains all the file paths that match the specified wildcard pattern.
patterns
filepaths
parameters can be a single string or an array of strings. I
f the matching pattern is
!
a
t the beginning, the path is matched from the excluded pattern from the returned array.
Patterns are processed in the specified order, so the order in which files are included and excluded is important.
grunt.file.match([options, ] patterns, filepaths)
options
also support all
the options provided by the minimatch
library. F
or example,
options.matchBase
true, the pattern matches the base name that contains the slash, even if there is no slash in the pattern.
For example:
*.js
matches
path/to/file.js
file path.
This method contains
grunt.file.match
method, but if it matches any file, it simply
ture
otherwise
false
Detects the existence of a given path and returns the value of the boolean type.
Like the path.js method in Node, this method connects all parameters together and normalizes the results.
grunt.file.exists(path1 [, path2 [, ...]])
Whether the given path is a symbolic link returns the value of the boolean type.
Like .js the path.join method in Node, this method connects all parameters together and normalizes the results.
grunt.file.isLink(path1 [, path2 [, ...]])
If the path does not exist, the false is returned.
Is the specified path a directory? Returns the value of the boolean type.
Like .js the path.join method in Node, this method connects all parameters together and normalizes the results.
grunt.file.isDir(path1 [, path2 [, ...]])
If the path does not exist, it also returns false.
Is the specified path a file? Returns the value of the boolean type.
Like .js the path.join method in Node, this method connects all parameters together and normalizes the results.
grunt.file.isFile(path1 [, path2 [, ...]])
If the path does not exist, false is returned.
Is the specified file path an absolute path? Returns the value of the boolean type.
Like .js the path.join method in Node, this method connects all parameters together and normalizes the results.
grunt.file.isPathAbsolute(path1 [, path2 [, ...]])
Are all the paths given the same path? Returns the value of the boolean type.
grunt.file.arePathsEquivalent(path1 [, path2 [, ...]])
Are all descendant paths included in the specified ancestor path? Returns the value of the boolean type.
Note: There is no need to check if the path really exists.
grunt.file.doesPathContain(ancestorPath, descendantPath1 [, descendantPath2 [, ...]])
Is the specified file path CWD? Returns the value of the boolean type.
Like .js the path.join method in Node, this method connects all parameters together and normalizes the results.
grunt.file.isPathCwd(path1 [, path2 [, ...]])
Is the specified file path in the CWD? N ote: The CWD is not in the CWD. Returns the value of the boolean type.
Like .js the path.join method in Node, this method connects all parameters together and normalizes the results.
grunt.file.isPathInCwd(path1 [, path2 [, ...]])
Change Grunt's current working directory (CWD). B
y default, all file paths are relative
Gruntfile
files.
This function works in the same way as the
--base
command line argument.
grunt.file.setBase(path1 [, path2 [, ...]])
Like .js the path.join method in Node, this method connects all parameters together and normalizes the results.
Not recommended
All external tool libraries listed below are no longer recommended.
Use npm to manage the dependencies on third-party tool libraries in your project.
For example, if you need
to use Lo-Dash,
install it first with
npm install lodash
and then use it in the
Gruntfile
var _ = require('lodash');
Not recommended
glob - File globbing utility.
Not recommended
minimatch - File pattern matching utility.
Not recommended
findup-sync - Search upwards for matching file patterns.