Installations
npm install fs-extra2
Developer Guide
Typescript
No
Module System
CommonJS
Node Version
16.17.0
NPM Version
8.15.0
Score
76
Supply Chain
99.4
Quality
75.9
Maintenance
100
Vulnerability
100
License
Releases
Unable to fetch releases
Contributors
Languages
JavaScript (100%)
Love this project? Help keep it running — sponsor us today! 🚀
Developer
jprichardson
Download Statistics
Total Downloads
348,791
Last Day
46
Last Week
934
Last Month
4,745
Last Year
91,012
GitHub Statistics
9,521 Stars
1,117 Commits
774 Forks
93 Watching
2 Branches
90 Contributors
Bundle Size
25.75 kB
Minified
7.70 kB
Minified + Gzipped
Package Meta Information
Latest Version
1.0.1
Package Id
fs-extra2@1.0.1
Unpacked Size
60.50 kB
Size
16.93 kB
File Count
33
NPM Version
8.15.0
Node Version
16.17.0
Publised On
09 Jun 2024
Total Downloads
Cumulative downloads
Total Downloads
348,791
Last day
-74.2%
46
Compared to previous day
Last week
-23.4%
934
Compared to previous week
Last month
-7.9%
4,745
Compared to previous month
Last year
6.7%
91,012
Compared to previous year
Daily Downloads
Weekly Downloads
Monthly Downloads
Yearly Downloads
Dependencies
3
Node.js: fs-extra
fs-extra
adds file system methods that aren't included in the native fs
module. It is a drop in replacement for fs
.
Why?
I got tired of including mkdirp
, rimraf
, and cp -r
in most of my projects.
Installation
npm install --save fs-extra
Usage
fs-extra
is a drop in replacement for native fs
. All methods in fs
are unmodified and attached to fs-extra
.
You don't ever need to include the original fs
module again:
1var fs = require('fs') // this is no longer necessary
you can now do this:
1var fs = require('fs-extra')
or if you prefer to make it clear that you're using fs-extra
and not fs
, you may want
to name your fs
variable fse
like so:
1var fse = require('fs-extra')
you can also keep both, but it's redundant:
1var fs = require('fs') 2var fse = require('fs-extra')
Methods
- copy
- copySync
- createOutputStream
- emptyDir
- emptyDirSync
- ensureFile
- ensureFileSync
- ensureDir
- ensureDirSync
- ensureLink
- ensureLinkSync
- ensureSymlink
- ensureSymlinkSync
- mkdirs
- mkdirsSync
- move
- outputFile
- outputFileSync
- outputJson
- outputJsonSync
- readJson
- readJsonSync
- remove
- removeSync
- writeJson
- writeJsonSync
NOTE: You can still use the native Node.js methods. They are copied over to fs-extra
.
copy()
copy(src, dest, [options], callback)
Copy a file or directory. The directory can have contents. Like cp -r
.
Options:
clobber (boolean): overwrite existing file or directory
preserveTimestamps (boolean): will set last modification and access times to the ones of the original source files, default is false
.
Sync: copySync()
Examples:
1var fs = require('fs-extra') 2 3fs.copy('/tmp/myfile', '/tmp/mynewfile', function (err) { 4 if (err) return console.error(err) 5 console.log("success!") 6}) // copies file 7 8fs.copy('/tmp/mydir', '/tmp/mynewdir', function (err) { 9 if (err) return console.error(err) 10 console.log('success!') 11}) // copies directory, even if it has subdirectories or files
createOutputStream(file, [options])
Exactly like createWriteStream
, but if the directory does not exist, it's created.
Examples:
1var fs = require('fs-extra') 2 3// if /tmp/some does not exist, it is created 4var ws = fs.createOutputStream('/tmp/some/file.txt') 5ws.write('hello\n')
Note on naming: you'll notice that fs-extra has some methods like fs.outputJson
, fs.outputFile
, etc that use the
word output
to denote that if the containing directory does not exist, it should be created. If you can think of a
better succinct nomenclature for these methods, please open an issue for discussion. Thanks.
emptyDir(dir, [callback])
Ensures that a directory is empty. If the directory does not exist, it is created. The directory itself is not deleted.
Alias: emptydir()
Sync: emptyDirSync()
, emptydirSync()
Example:
1var fs = require('fs-extra') 2 3// assume this directory has a lot of files and folders 4fs.emptyDir('/tmp/some/dir', function (err) { 5 if (!err) console.log('success!') 6})
ensureFile(file, callback)
Ensures that the file exists. If the file that is requested to be created is in directories that do not exist, these directories are created. If the file already exists, it is NOT MODIFIED.
Alias: createFile()
Sync: createFileSync()
,ensureFileSync()
Example:
1var fs = require('fs-extra') 2 3var file = '/tmp/this/path/does/not/exist/file.txt' 4fs.ensureFile(file, function (err) { 5 console.log(err) // => null 6 // file has now been created, including the directory it is to be placed in 7})
ensureDir(dir, callback)
Ensures that the directory exists. If the directory structure does not exist, it is created.
Sync: ensureDirSync()
Example:
1var fs = require('fs-extra') 2 3var dir = '/tmp/this/path/does/not/exist' 4fs.ensureDir(dir, function (err) { 5 console.log(err) // => null 6 // dir has now been created, including the directory it is to be placed in 7})
ensureLink(srcpath, dstpath, callback)
Ensures that the link exists. If the directory structure does not exist, it is created.
Sync: ensureLinkSync()
Example:
1var fs = require('fs-extra') 2 3var srcpath = '/tmp/file.txt' 4var dstpath = '/tmp/this/path/does/not/exist/file.txt' 5fs.ensureLink(srcpath, dstpath, function (err) { 6 console.log(err) // => null 7 // link has now been created, including the directory it is to be placed in 8})
ensureSymlink(srcpath, dstpath, [type], callback)
Ensures that the symlink exists. If the directory structure does not exist, it is created.
Sync: ensureSymlinkSync()
Example:
1var fs = require('fs-extra') 2 3var srcpath = '/tmp/file.txt' 4var dstpath = '/tmp/this/path/does/not/exist/file.txt' 5fs.ensureSymlink(srcpath, dstpath, function (err) { 6 console.log(err) // => null 7 // symlink has now been created, including the directory it is to be placed in 8})
mkdirs(dir, callback)
Creates a directory. If the parent hierarchy doesn't exist, it's created. Like mkdir -p
.
Alias: mkdirp()
Sync: mkdirsSync()
/ mkdirpSync()
Examples:
1var fs = require('fs-extra') 2 3fs.mkdirs('/tmp/some/long/path/that/prob/doesnt/exist', function (err) { 4 if (err) return console.error(err) 5 console.log("success!") 6}) 7 8fs.mkdirsSync('/tmp/another/path')
move(src, dest, [options], callback)
Moves a file or directory, even across devices.
Options: clobber (boolean): overwrite existing file or directory limit (number): number of concurrent moves, see ncp for more information
Example:
1var fs = require('fs-extra') 2 3fs.move('/tmp/somefile', '/tmp/does/not/exist/yet/somefile', function (err) { 4 if (err) return console.error(err) 5 console.log("success!") 6})
outputFile(file, data, callback)
Almost the same as writeFile
(i.e. it overwrites), except that if the parent directory does not exist, it's created.
Sync: outputFileSync()
Example:
1var fs = require('fs-extra') 2var file = '/tmp/this/path/does/not/exist/file.txt' 3 4fs.outputFile(file, 'hello!', function (err) { 5 console.log(err) // => null 6 7 fs.readFile(file, 'utf8', function (err, data) { 8 console.log(data) // => hello! 9 }) 10})
outputJson(file, data, [options], callback)
Almost the same as writeJson
, except that if the directory does not exist, it's created.
options
are what you'd pass to jsonFile.writeFile()
.
Alias: outputJSON()
Sync: outputJsonSync()
, outputJSONSync()
Example:
1var fs = require('fs-extra') 2var file = '/tmp/this/path/does/not/exist/file.txt' 3 4fs.outputJson(file, {name: 'JP'}, function (err) { 5 console.log(err) // => null 6 7 fs.readJson(file, function(err, data) { 8 console.log(data.name) // => JP 9 }) 10})
readJson(file, [options], callback)
Reads a JSON file and then parses it into an object. options
are the same
that you'd pass to jsonFile.readFile
.
Alias: readJSON()
Sync: readJsonSync()
, readJSONSync()
Example:
1var fs = require('fs-extra') 2 3fs.readJson('./package.json', function (err, packageObj) { 4 console.log(packageObj.version) // => 0.1.3 5})
readJsonSync()
can take a throws
option set to false
and it won't throw if the JSON is invalid. Example:
1var fs = require('fs-extra') 2var file = path.join('/tmp/some-invalid.json') 3var data = '{not valid JSON' 4fs.writeFileSync(file, data) 5 6var obj = fs.readJsonSync(file, {throws: false}) 7console.log(obj) // => null
remove(dir, callback)
Removes a file or directory. The directory can have contents. Like rm -rf
.
Sync: removeSync()
Examples:
1var fs = require('fs-extra') 2 3fs.remove('/tmp/myfile', function (err) { 4 if (err) return console.error(err) 5 6 console.log('success!') 7}) 8 9fs.removeSync('/home/jprichardson') //I just deleted my entire HOME directory.
writeJson(file, object, [options], callback)
Writes an object to a JSON file. options
are the same that
you'd pass to jsonFile.writeFile()
.
Alias: writeJSON()
Sync: writeJsonSync()
, writeJSONSync()
Example:
1var fs = require('fs-extra') 2fs.writeJson('./package.json', {name: 'fs-extra'}, function (err) { 3 console.log(err) 4})
Third Party
Promises
Use Bluebird. See https://github.com/petkaantonov/bluebird/blob/master/API.md#promisification. fs-extra
is
explicitly listed as supported.
1var Promise = require('bluebird') 2var fs = Promise.promisifyAll(require('fs-extra'))
Or you can use the package fs-extra-promise
that marries the two together.
TypeScript
If you like TypeScript, you can use fs-extra
with it: https://github.com/borisyankov/DefinitelyTyped/tree/master/fs-extra
File / Directory Watching
If you want to watch for changes to files or directories, then you should use chokidar.
Misc.
- mfs - Monitor your fs-extra calls.
Hacking on fs-extra
Wanna hack on fs-extra
? Great! Your help is needed! fs-extra is one of the most depended upon Node.js packages. This project
uses JavaScript Standard Style - if the name or style choices bother you,
you're gonna have to get over it :) If standard
is good enough for npm
, it's good enough for fs-extra
.
What's needed?
- First, take a look at existing issues. Those are probably going to be where the priority lies.
- More tests for edge cases. Specifically on different platforms. There can never be enough tests.
- Really really help with the Windows tests. See appveyor outputs for more info.
- Improve test coverage. See coveralls output for more info.
- A directory walker. Probably this one: https://github.com/thlorenz/readdirp imported into
fs-extra
. - After the directory walker is integrated, any function that needs to traverse directories like
copy
,remove
, ormkdirs
should be built on top of it. - After the aforementioned functions are built on the directory walker,
fs-extra
should then explicitly support wildcards.
Note: If you make any big changes, you should definitely post an issue for discussion first.
Naming
I put a lot of thought into the naming of these functions. Inspired by @coolaj86's request. So he deserves much of the credit for raising the issue. See discussion(s) here:
- https://github.com/jprichardson/node-fs-extra/issues/2
- https://github.com/flatiron/utile/issues/11
- https://github.com/ryanmcgrath/wrench-js/issues/29
- https://github.com/substack/node-mkdirp/issues/17
First, I believe that in as many cases as possible, the Node.js naming schemes should be chosen. However, there are problems with the Node.js own naming schemes.
For example, fs.readFile()
and fs.readdir()
: the F is capitalized in File and the d is not capitalized in dir. Perhaps a bit pedantic, but they should still be consistent. Also, Node.js has chosen a lot of POSIX naming schemes, which I believe is great. See: fs.mkdir()
, fs.rmdir()
, fs.chown()
, etc.
We have a dilemma though. How do you consistently name methods that perform the following POSIX commands: cp
, cp -r
, mkdir -p
, and rm -rf
?
My perspective: when in doubt, err on the side of simplicity. A directory is just a hierarchical grouping of directories and files. Consider that for a moment. So when you want to copy it or remove it, in most cases you'll want to copy or remove all of its contents. When you want to create a directory, if the directory that it's suppose to be contained in does not exist, then in most cases you'll want to create that too.
So, if you want to remove a file or a directory regardless of whether it has contents, just call fs.remove(path)
. If you want to copy a file or a directory whether it has contents, just call fs.copy(source, destination)
. If you want to create a directory regardless of whether its parent directories exist, just call fs.mkdirs(path)
or fs.mkdirp(path)
.
Credit
fs-extra
wouldn't be possible without using the modules from the following authors:
License
Licensed under MIT
Copyright (c) 2011-2015 JP Richardson
No vulnerabilities found.
Reason
no dangerous workflow patterns detected
Reason
GitHub workflow tokens follow principle of least privilege
Details
- Info: topLevel 'contents' permission set to 'read': .github/workflows/ci.yml:8
- Info: no jobLevel write permissions found
Reason
no binaries found in the repo
Reason
license file detected
Details
- Info: project has a license file: LICENSE:0
- Info: FSF or OSI recognized license: MIT License: LICENSE:0
Reason
0 existing vulnerabilities detected
Reason
2 commit(s) and 4 issue activity found in the last 90 days -- score normalized to 5
Reason
Found 17/30 approved changesets -- score normalized to 5
Reason
dependency not pinned by hash detected -- score normalized to 0
Details
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/ci.yml:18: update your workflow using https://app.stepsecurity.io/secureworkflow/jprichardson/node-fs-extra/ci.yml/master?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/ci.yml:20: update your workflow using https://app.stepsecurity.io/secureworkflow/jprichardson/node-fs-extra/ci.yml/master?enable=pin
- Warn: npmCommand not pinned by hash: .github/workflows/ci.yml:24
- Info: 0 out of 2 GitHub-owned GitHubAction dependencies pinned
- Info: 0 out of 1 npmCommand dependencies pinned
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
- Warn: no security policy file detected
- Warn: no security file to analyze
- Warn: no security file to analyze
- Warn: no security file to analyze
Reason
project is not fuzzed
Details
- Warn: no fuzzer integrations found
Reason
branch protection not enabled on development/release branches
Details
- Warn: branch protection not enabled for branch 'master'
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
- Warn: 0 commits out of 24 are checked with a SAST tool
Score
5.3
/10
Last Scanned on 2025-02-03
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More