31
• fs.readFile() – Yep, it reads a file and passes
the data from it to a
function you supply, wherein you can do whatever you like with it.
And yes, there is, of course, a matching fs.writeFile() method,
with which you can do things like writing a JavaScript object that you
JSON.stringify() to marshal into a string to a file.
• fs.unlink() – If you want to delete a file, you actually want to
“unlink”
it in POSIX-speak, so this module offers an fs.unlink()
method. Pass it the path to the file, and thy bidding will be done!
(You can also remove symlinks with this.)
• fs.mkdir() – Not only can you work with files with this module but
you can work with directories too. The fs.mkdir() method allows
you to create directories. I should also note at this point that all
the methods so far also accept an object with various options. For
example, this method allows you to pass a mode key in the options
object to specify the permissions for the directory (although note
that this is not supported on Windows). This is a typical pattern that
repeats itself frequently in this module as well.
To delete a directory,
the fs.rmdir() method is provided.
• fs.stat() – If you’re looking for information about a file or directory,
things like its size, last access time, and when it was created, then
fs.stat() is your friend. It returns an fs.Stats object, which is an
object within the File System module,
and it contains many pieces
of information including the size of the file or directory (size) and
when it was created (birthtime).
• fs.readdir() – This method allows you to read in the contents of a
directory given its path, and returns to you an array of filenames, or
an array of Buffer objects containing the names, or an array of
fs.Dirent objects, one per file (which you get depends on the options
you pass in, with an array of string filenames being the default).
In
later versions of Node, starting around v10, a new subsection of the File System
module was introduced: the Promises API. Basically, it provides methods matching
the fs methods seen here and most of the others this module offers, but that return
Chapter 2 a Few More words: advanCed node and npM
32
Promises. So, if you prefer a Promise-based coding style (or async/await on top of that),
then have a look at the section on that in the docs. Other than different names (e.g., fs.
fsPromises.copyFile() and fs.fsPromises.readFile()) and the obvious syntactic
differences, they otherwise are mostly the same as the non-Promise versions.
Do'stlaringiz bilan baham: