Repository: jprichardson/node-fs-extra Branch: master Commit: 353a29b18c88 Files: 165 Total size: 456.2 KB Directory structure: gitextract_ch38kmlm/ ├── .github/ │ ├── issue_template.md │ └── workflows/ │ └── ci.yml ├── .gitignore ├── .npmrc ├── CHANGELOG.md ├── LICENSE ├── README.md ├── docs/ │ ├── copy-sync.md │ ├── copy.md │ ├── emptyDir-sync.md │ ├── emptyDir.md │ ├── ensureDir-sync.md │ ├── ensureDir.md │ ├── ensureFile-sync.md │ ├── ensureFile.md │ ├── ensureLink-sync.md │ ├── ensureLink.md │ ├── ensureSymlink-sync.md │ ├── ensureSymlink.md │ ├── fs-read-write-writev.md │ ├── move-sync.md │ ├── move.md │ ├── outputFile-sync.md │ ├── outputFile.md │ ├── outputJson-sync.md │ ├── outputJson.md │ ├── pathExists-sync.md │ ├── pathExists.md │ ├── readJson-sync.md │ ├── readJson.md │ ├── remove-sync.md │ ├── remove.md │ ├── writeJson-sync.md │ └── writeJson.md ├── lib/ │ ├── __tests__/ │ │ └── promise.test.js │ ├── copy/ │ │ ├── __tests__/ │ │ │ ├── copy-broken-symlink.test.js │ │ │ ├── copy-case-insensitive-paths.test.js │ │ │ ├── copy-dev-null.test.js │ │ │ ├── copy-gh-89.test.js │ │ │ ├── copy-permissions.test.js │ │ │ ├── copy-preserve-timestamp.test.js │ │ │ ├── copy-prevent-copying-identical.test.js │ │ │ ├── copy-prevent-copying-into-itself.test.js │ │ │ ├── copy-readonly-dir.test.js │ │ │ ├── copy-symlink-same-target.test.js │ │ │ ├── copy-sync-broken-symlink.test.js │ │ │ ├── copy-sync-case-insensitive-paths.test.js │ │ │ ├── copy-sync-dir.test.js │ │ │ ├── copy-sync-file.test.js │ │ │ ├── copy-sync-preserve-timestamp.test.js │ │ │ ├── copy-sync-prevent-copying-identical.test.js │ │ │ ├── copy-sync-prevent-copying-into-itself.test.js │ │ │ ├── copy-sync-readonly-dir.test.js │ │ │ ├── copy-sync-symlink-same-target.test.js │ │ │ ├── copy-sync-symlink.test.js │ │ │ ├── copy.test.js │ │ │ └── ncp/ │ │ │ ├── README.md │ │ │ ├── broken-symlink.test.js │ │ │ ├── fixtures/ │ │ │ │ ├── modified-files/ │ │ │ │ │ ├── out/ │ │ │ │ │ │ └── a │ │ │ │ │ └── src/ │ │ │ │ │ └── a │ │ │ │ └── regular-fixtures/ │ │ │ │ ├── out/ │ │ │ │ │ ├── a │ │ │ │ │ ├── b │ │ │ │ │ ├── c │ │ │ │ │ ├── d │ │ │ │ │ ├── e │ │ │ │ │ ├── f │ │ │ │ │ └── sub/ │ │ │ │ │ ├── a │ │ │ │ │ └── b │ │ │ │ └── src/ │ │ │ │ ├── a │ │ │ │ ├── b │ │ │ │ ├── c │ │ │ │ ├── d │ │ │ │ ├── e │ │ │ │ ├── f │ │ │ │ └── sub/ │ │ │ │ ├── a │ │ │ │ └── b │ │ │ ├── ncp-error-perm.test.js │ │ │ ├── ncp.test.js │ │ │ └── symlink.test.js │ │ ├── copy-sync.js │ │ ├── copy.js │ │ └── index.js │ ├── empty/ │ │ ├── __tests__/ │ │ │ ├── empty-dir-sync.test.js │ │ │ └── empty-dir.test.js │ │ └── index.js │ ├── ensure/ │ │ ├── __tests__/ │ │ │ ├── create.test.js │ │ │ ├── ensure.test.js │ │ │ ├── link.test.js │ │ │ ├── symlink-paths.test.js │ │ │ ├── symlink-type.test.js │ │ │ └── symlink.test.js │ │ ├── file.js │ │ ├── index.js │ │ ├── link.js │ │ ├── symlink-paths.js │ │ ├── symlink-type.js │ │ └── symlink.js │ ├── esm.mjs │ ├── fs/ │ │ ├── __tests__/ │ │ │ ├── copyFile.test.js │ │ │ ├── fs-integration.test.js │ │ │ ├── multi-param.test.js │ │ │ ├── mz.test.js │ │ │ ├── realpath.test.js │ │ │ └── rm.test.js │ │ └── index.js │ ├── index.js │ ├── json/ │ │ ├── __tests__/ │ │ │ ├── jsonfile-integration.test.js │ │ │ ├── output-json-sync.test.js │ │ │ ├── output-json.test.js │ │ │ ├── promise-support.test.js │ │ │ └── read.test.js │ │ ├── index.js │ │ ├── jsonfile.js │ │ ├── output-json-sync.js │ │ └── output-json.js │ ├── mkdirs/ │ │ ├── __tests__/ │ │ │ ├── chmod.test.js │ │ │ ├── clobber.test.js │ │ │ ├── issue-209.test.js │ │ │ ├── issue-93.test.js │ │ │ ├── mkdir.test.js │ │ │ ├── mkdirp.test.js │ │ │ ├── opts-undef.test.js │ │ │ ├── perm.test.js │ │ │ ├── perm_sync.test.js │ │ │ ├── race.test.js │ │ │ ├── rel.test.js │ │ │ ├── root.test.js │ │ │ └── sync.test.js │ │ ├── index.js │ │ ├── make-dir.js │ │ └── utils.js │ ├── move/ │ │ ├── __tests__/ │ │ │ ├── cross-device-utils.js │ │ │ ├── move-case-insensitive-paths.test.js │ │ │ ├── move-preserve-timestamp.test.js │ │ │ ├── move-prevent-moving-identical.test.js │ │ │ ├── move-prevent-moving-into-itself.test.js │ │ │ ├── move-sync-case-insensitive-paths.test.js │ │ │ ├── move-sync-preserve-timestamp.test.js │ │ │ ├── move-sync-prevent-moving-identical.test.js │ │ │ ├── move-sync-prevent-moving-into-itself.test.js │ │ │ ├── move-sync.test.js │ │ │ └── move.test.js │ │ ├── index.js │ │ ├── move-sync.js │ │ └── move.js │ ├── output-file/ │ │ ├── __tests__/ │ │ │ └── output.test.js │ │ └── index.js │ ├── path-exists/ │ │ ├── __tests__/ │ │ │ ├── path-exists-sync.test.js │ │ │ └── path-exists.test.js │ │ └── index.js │ ├── remove/ │ │ ├── __tests__/ │ │ │ ├── remove-dir.test.js │ │ │ ├── remove-file.test.js │ │ │ ├── remove-sync-dir.test.js │ │ │ ├── remove-sync-file.test.js │ │ │ └── remove.test.js │ │ └── index.js │ └── util/ │ ├── __tests__/ │ │ ├── stat.test.js │ │ └── utimes.test.js │ ├── async.js │ ├── stat.js │ └── utimes.js ├── package.json ├── test/ │ └── readme.md ├── test.js └── test.mjs ================================================ FILE CONTENTS ================================================ ================================================ FILE: .github/issue_template.md ================================================ - **Operating System:** - **Node.js version:** - **`fs-extra` version:** ================================================ FILE: .github/workflows/ci.yml ================================================ name: Node.js CI on: push: branches: master pull_request: permissions: contents: read # to fetch code (actions/checkout) jobs: test: strategy: matrix: node: [14.x, 16.x, 18.x, 20.x, 22.x, 24.x] os: [ubuntu-latest, macos-15-intel, windows-latest] runs-on: ${{ matrix.os }} steps: - uses: actions/checkout@v3 - name: Use Node.js ${{ matrix.node }} uses: actions/setup-node@v3 with: node-version: ${{ matrix.node }} - run: npm install - run: npm test ================================================ FILE: .gitignore ================================================ .nyc_output/ coverage/ node_modules/ .idea *.iml npm-debug.log ================================================ FILE: .npmrc ================================================ package-lock=false ================================================ FILE: CHANGELOG.md ================================================ 11.3.4 / 2026-03-03 ------------------- - Fix bug where calling `ensureSymlink`/`ensureSymlinkSync` with a relative `srcPath` would fail if the symlink already existed ([#1038](https://github.com/jprichardson/node-fs-extra/issues/1038), [#1064](https://github.com/jprichardson/node-fs-extra/pull/1064)) 11.3.3 / 2025-12-18 ------------------- - Fix copying symlink when destination is a symlink to the same target ([#1019](https://github.com/jprichardson/node-fs-extra/issues/1019), [#1060](https://github.com/jprichardson/node-fs-extra/pull/1060)) 11.3.2 / 2025-09-15 ------------------- - Fix spurrious `UnhandledPromiseRejectionWarning` that could occur when calling `.copy()` in some cases ([#1056](https://github.com/jprichardson/node-fs-extra/issues/1056), [#1058](https://github.com/jprichardson/node-fs-extra/pull/1058)) 11.3.1 / 2025-08-05 ------------------- - Fix case where `move`/`moveSync` could incorrectly think files are identical on Windows ([#1050](https://github.com/jprichardson/node-fs-extra/pull/1050)) 11.3.0 / 2025-01-15 ------------------- - Add promise support for newer `fs` methods ([#1044](https://github.com/jprichardson/node-fs-extra/issues/1044), [#1045](https://github.com/jprichardson/node-fs-extra/pull/1045)) - Use `fs.opendir` in `copy()`/`copySync()` for better perf/scalability ([#972](https://github.com/jprichardson/node-fs-extra/issues/972), [#1028](https://github.com/jprichardson/node-fs-extra/pull/1028)) 11.2.0 / 2023-11-27 ------------------- - Copy directory contents in parallel for better performance ([#1026](https://github.com/jprichardson/node-fs-extra/pull/1026)) - Refactor internal code to use `async`/`await` ([#1020](https://github.com/jprichardson/node-fs-extra/issues/1020)) 11.1.1 / 2023-03-20 ------------------- - Preserve timestamps when moving files across devices ([#992](https://github.com/jprichardson/node-fs-extra/issues/992), [#994](https://github.com/jprichardson/node-fs-extra/pull/994)) 11.1.0 / 2022-11-29 ------------------- - Re-add `main` field to `package.json` for better TypeScript compatibility ([#979](https://github.com/jprichardson/node-fs-extra/issues/979), [#981](https://github.com/jprichardson/node-fs-extra/pull/981)) 11.0.0 / 2022-11-28 ------------------- ### Breaking Changes - Don't allow requiring `fs-extra/lib/SOMETHING` (switched to `exports`) ([#974](https://github.com/jprichardson/node-fs-extra/pull/974)) - Require Node v14.14+ ([#968](https://github.com/jprichardson/node-fs-extra/issues/968), [#969](https://github.com/jprichardson/node-fs-extra/pull/969)) ### New Features - Add `fs-extra/esm` for ESM named export support; see [docs](https://github.com/jprichardson/node-fs-extra#esm) for details ([#746](https://github.com/jprichardson/node-fs-extra/issues/746), [#974](https://github.com/jprichardson/node-fs-extra/pull/974)) - Add promise support for `fs.readv()` ([#970](https://github.com/jprichardson/node-fs-extra/pull/970)) ### Bugfixes - Don't `stat` filtered items in `copy*` ([#965](https://github.com/jprichardson/node-fs-extra/issues/965), [#971](https://github.com/jprichardson/node-fs-extra/pull/971)) - Remove buggy stats check in `copy` ([#918](https://github.com/jprichardson/node-fs-extra/issues/918), [#976](https://github.com/jprichardson/node-fs-extra/pull/976)) 10.1.0 / 2022-04-16 ------------------- - Warn if `fs.realpath.native` does not exist, instead of erroring ([#953](https://github.com/jprichardson/node-fs-extra/pull/953)) - Allow explicitly passing `undefined` options to `move()` ([#947](https://github.com/jprichardson/node-fs-extra/issues/947), [#955](https://github.com/jprichardson/node-fs-extra/pull/955)) - Use `process.emitWarning` instead of `console.warn` ([#954](https://github.com/jprichardson/node-fs-extra/pull/954)) 10.0.1 / 2022-02-22 ------------------- - Add `sideEffects: false` to `package.json` ([#941](https://github.com/jprichardson/node-fs-extra/pull/941)) 10.0.0 / 2021-05-03 ------------------- ### Breaking changes - Require Node.js v12+ ([#886](https://github.com/jprichardson/node-fs-extra/issues/886), [#893](https://github.com/jprichardson/node-fs-extra/pull/893), [#890](https://github.com/jprichardson/node-fs-extra/pull/890), [#894](https://github.com/jprichardson/node-fs-extra/pull/894), [#895]( https://github.com/jprichardson/node-fs-extra/pull/895)) - Allow copying broken symlinks ([#779](https://github.com/jprichardson/node-fs-extra/pull/779), [#765](https://github.com/jprichardson/node-fs-extra/issues/765), [#638](https://github.com/jprichardson/node-fs-extra/issues/638), [#761](https://github.com/jprichardson/node-fs-extra/issues/761)) **The following changes, although technically semver-major, will not affect the vast majority of users:** - Ensure correct type when destination exists for `ensureLink*()`/`ensureSymlink*()` ([#826](https://github.com/jprichardson/node-fs-extra/pull/826), [#786](https://github.com/jprichardson/node-fs-extra/issues/786), [#870](https://github.com/jprichardson/node-fs-extra/issues/870)) - Error when attempting to `copy*()` unknown file type ([#880](https://github.com/jprichardson/node-fs-extra/pull/880)) - Remove undocumented options for `remove*()` ([#882](https://github.com/jprichardson/node-fs-extra/pull/882)) ### Improvements - Allow changing case of filenames with `move*()`, even on technically case-insensitive filesystems ([#759](https://github.com/jprichardson/node-fs-extra/issues/759), [#801](https://github.com/jprichardson/node-fs-extra/pull/801)) - Use native `fs.rm*()` for `remove*()` in environments that support it ([#882](https://github.com/jprichardson/node-fs-extra/pull/882), [#806](https://github.com/jprichardson/node-fs-extra/issues/806)) - Improve `emptyDir()` performance ([#885](https://github.com/jprichardson/node-fs-extra/pull/885)) ### Bugfixes - Ensure `copy*()`'s `filter` function is not called more than necessary ([#883](https://github.com/jprichardson/node-fs-extra/pull/883), [#809](https://github.com/jprichardson/node-fs-extra/issues/809)) - Fix `move*()` raising `EPERM` error when moving a file to the root of a drive on Windows ([#897](https://github.com/jprichardson/node-fs-extra/pull/897), [#819](https://github.com/jprichardson/node-fs-extra/issues/819)) ### Miscellaneous changes - Do not use `at-least-node` as a dependency ([#896](https://github.com/jprichardson/node-fs-extra/pull/896)) - Improve documentation ([#888](https://github.com/jprichardson/node-fs-extra/pull/888), [#830](https://github.com/jprichardson/node-fs-extra/issues/830), [#884](https://github.com/jprichardson/node-fs-extra/pull/884), [#843](https://github.com/jprichardson/node-fs-extra/issues/843)) 9.1.0 / 2021-01-19 ------------------ - Add promise support for `fs.rm()` ([#841](https://github.com/jprichardson/node-fs-extra/issues/841), [#860](https://github.com/jprichardson/node-fs-extra/pull/860)) - Upgrade universalify for performance improvments ([#825](https://github.com/jprichardson/node-fs-extra/pull/825)) 9.0.1 / 2020-06-03 ------------------ - Fix issue with `ensureFile()` when used with Jest on Windows ([#804](https://github.com/jprichardson/node-fs-extra/issues/804), [#805](https://github.com/jprichardson/node-fs-extra/pull/805)) - Remove unneeded `process.umask()` call ([#791](https://github.com/jprichardson/node-fs-extra/pull/791)) - Docs improvements ([#753](https://github.com/jprichardson/node-fs-extra/pull/753), [#795](https://github.com/jprichardson/node-fs-extra/pull/795), [#797](https://github.com/jprichardson/node-fs-extra/pull/797)) 9.0.0 / 2020-03-19 ------------------ ### Breaking changes - Requires Node.js version 10 or greater ([#725](https://github.com/jprichardson/node-fs-extra/issues/725), [#751](https://github.com/jprichardson/node-fs-extra/pull/751)) - Switched `ensureDir*` to use a fork of https://github.com/sindresorhus/make-dir to make use of native recursive `fs.mkdir` where possible ([#619](https://github.com/jprichardson/node-fs-extra/issues/619), [#756](https://github.com/jprichardson/node-fs-extra/pull/756)) - Properly preserve `atime` for `copy*` with `preserveTimestamps` option ([#633](https://github.com/jprichardson/node-fs-extra/pull/633)) **The following changes, allthough technically breaking, will not affect the vast majority of users:** - `outputJson` now outputs objects as they were when the function was called, even if they are mutated later ([#702](https://github.com/jprichardson/node-fs-extra/issues/702), [#768](https://github.com/jprichardson/node-fs-extra/pull/768)) - Cannot pass `null` as an options parameter to `*Json*` methods ([#745](https://github.com/jprichardson/node-fs-extra/issues/745), [#768](https://github.com/jprichardson/node-fs-extra/pull/768)) ### Improvements - Add promise shims for `fs.writev` & `fs.opendir` ([#747](https://github.com/jprichardson/node-fs-extra/pull/747)) - Better errors for `ensureFile` ([#696](https://github.com/jprichardson/node-fs-extra/issues/696), [#744](https://github.com/jprichardson/node-fs-extra/pull/744)) - Better file comparison for older Node versions ([#694](https://github.com/jprichardson/node-fs-extra/pull/694)) ### Miscellaneous changes - Peformance optimizations ([#762](https://github.com/jprichardson/node-fs-extra/issues/762), [#764](https://github.com/jprichardson/node-fs-extra/pull/764)) - Add missing documentation for aliases ([#758](https://github.com/jprichardson/node-fs-extra/issues/758), [#766](https://github.com/jprichardson/node-fs-extra/pull/766)) - Update `universalify` dependency ([#767](https://github.com/jprichardson/node-fs-extra/pull/767)) 8.1.0 / 2019-06-28 ------------------ - Add support for promisified `fs.realpath.native` in Node v9.2+ ([#650](https://github.com/jprichardson/node-fs-extra/issues/650), [#682](https://github.com/jprichardson/node-fs-extra/pull/682)) - Update `graceful-fs` dependency ([#700](https://github.com/jprichardson/node-fs-extra/pull/700)) - Use `graceful-fs` everywhere ([#700](https://github.com/jprichardson/node-fs-extra/pull/700)) 8.0.1 / 2019-05-13 ------------------ - Fix bug `Maximum call stack size exceeded` error in `util/stat` ([#679](https://github.com/jprichardson/node-fs-extra/pull/679)) 8.0.0 / 2019-05-11 ------------------ **NOTE:** Node.js v6 support is deprecated, and will be dropped in the next major release. - Use `renameSync()` under the hood in `moveSync()` - Fix bug with bind-mounted directories in `copy*()` ([#613](https://github.com/jprichardson/node-fs-extra/issues/613), [#618](https://github.com/jprichardson/node-fs-extra/pull/618)) - Fix bug in `move()` with case-insensitive file systems - Use `fs.stat()`'s `bigint` option in `copy*()` & `move*()` where possible ([#657](https://github.com/jprichardson/node-fs-extra/issues/657)) 7.0.1 / 2018-11-07 ------------------ - Fix `removeSync()` on Windows, in some cases, it would error out with `ENOTEMPTY` ([#646](https://github.com/jprichardson/node-fs-extra/pull/646)) - Document `mode` option for `ensureDir*()` ([#587](https://github.com/jprichardson/node-fs-extra/pull/587)) - Don't include documentation files in npm package tarball ([#642](https://github.com/jprichardson/node-fs-extra/issues/642), [#643](https://github.com/jprichardson/node-fs-extra/pull/643)) 7.0.0 / 2018-07-16 ------------------ - **BREAKING:** Refine `copy*()` handling of symlinks to properly detect symlinks that point to the same file. ([#582](https://github.com/jprichardson/node-fs-extra/pull/582)) - Fix bug with copying write-protected directories ([#600](https://github.com/jprichardson/node-fs-extra/pull/600)) - Universalify `fs.lchmod()` ([#596](https://github.com/jprichardson/node-fs-extra/pull/596)) - Add `engines` field to `package.json` ([#580](https://github.com/jprichardson/node-fs-extra/pull/580)) 6.0.1 / 2018-05-09 ------------------ - Fix `fs.promises` `ExperimentalWarning` on Node v10.1.0 ([#578](https://github.com/jprichardson/node-fs-extra/pull/578)) 6.0.0 / 2018-05-01 ------------------ - Drop support for Node.js versions 4, 5, & 7 ([#564](https://github.com/jprichardson/node-fs-extra/pull/564)) - Rewrite `move` to use `fs.rename` where possible ([#549](https://github.com/jprichardson/node-fs-extra/pull/549)) - Don't convert relative paths to absolute paths for `filter` ([#554](https://github.com/jprichardson/node-fs-extra/pull/554)) - `copy*`'s behavior when `preserveTimestamps` is `false` has been OS-dependent since 5.0.0, but that's now explicitly noted in the docs ([#563](https://github.com/jprichardson/node-fs-extra/pull/563)) - Fix subdirectory detection for `copy*` & `move*` ([#541](https://github.com/jprichardson/node-fs-extra/pull/541)) - Handle case-insensitive paths correctly in `copy*` ([#568](https://github.com/jprichardson/node-fs-extra/pull/568)) 5.0.0 / 2017-12-11 ------------------ Significant refactor of `copy()` & `copySync()`, including breaking changes. No changes to other functions in this release. Huge thanks to **[@manidlou](https://github.com/manidlou)** for doing most of the work on this release. - The `filter` option can no longer be a RegExp (must be a function). This was deprecated since fs-extra v1.0.0. [#512](https://github.com/jprichardson/node-fs-extra/pull/512) - `copy()`'s `filter` option can now be a function that returns a Promise. [#518](https://github.com/jprichardson/node-fs-extra/pull/518) - `copy()` & `copySync()` now use `fs.copyFile()`/`fs.copyFileSync()` in environments that support it (currently Node 8.5.0+). Older Node versions still get the old implementation. [#505](https://github.com/jprichardson/node-fs-extra/pull/505) - Don't allow copying a directory into itself. [#83](https://github.com/jprichardson/node-fs-extra/issues/83) - Handle copying between identical files. [#198](https://github.com/jprichardson/node-fs-extra/issues/198) - Error out when copying an empty folder to a path that already exists. [#464](https://github.com/jprichardson/node-fs-extra/issues/464) - Don't create `dest`'s parent if the `filter` function aborts the `copy()` operation. [#517](https://github.com/jprichardson/node-fs-extra/pull/517) - Fix `writeStream` not being closed if there was an error in `copy()`. [#516](https://github.com/jprichardson/node-fs-extra/pull/516) 4.0.3 / 2017-12-05 ------------------ - Fix wrong `chmod` values in `fs.remove()` [#501](https://github.com/jprichardson/node-fs-extra/pull/501) - Fix `TypeError` on systems that don't have some `fs` operations like `lchown` [#520](https://github.com/jprichardson/node-fs-extra/pull/520) 4.0.2 / 2017-09-12 ------------------ - Added `EOL` option to `writeJson*` & `outputJson*` (via upgrade to jsonfile v4) - Added promise support to [`fs.copyFile()`](https://nodejs.org/api/fs.html#fs_fs_copyfile_src_dest_flags_callback) in Node 8.5+ - Added `.js` extension to `main` field in `package.json` for better tooling compatibility. [#485](https://github.com/jprichardson/node-fs-extra/pull/485) 4.0.1 / 2017-07-31 ------------------ ### Fixed - Previously, `ensureFile()` & `ensureFileSync()` would do nothing if the path was a directory. Now, they error out for consistency with `ensureDir()`. [#465](https://github.com/jprichardson/node-fs-extra/issues/465), [#466](https://github.com/jprichardson/node-fs-extra/pull/466), [#470](https://github.com/jprichardson/node-fs-extra/issues/470) 4.0.0 / 2017-07-14 ------------------ ### Changed - **BREAKING:** The promisified versions of `fs.read()` & `fs.write()` now return objects. See [the docs](docs/fs-read-write.md) for details. [#436](https://github.com/jprichardson/node-fs-extra/issues/436), [#449](https://github.com/jprichardson/node-fs-extra/pull/449) - `fs.move()` now errors out when destination is a subdirectory of source. [#458](https://github.com/jprichardson/node-fs-extra/pull/458) - Applied upstream fixes from `rimraf` to `fs.remove()` & `fs.removeSync()`. [#459](https://github.com/jprichardson/node-fs-extra/pull/459) ### Fixed - Got `fs.outputJSONSync()` working again; it was broken due to refactoring. [#428](https://github.com/jprichardson/node-fs-extra/pull/428) Also clarified the docs in a few places. 3.0.1 / 2017-05-04 ------------------ - Fix bug in `move()` & `moveSync()` when source and destination are the same, and source does not exist. [#415](https://github.com/jprichardson/node-fs-extra/pull/415) 3.0.0 / 2017-04-27 ------------------ ### Added - **BREAKING:** Added Promise support. All asynchronous native fs methods and fs-extra methods now return a promise if the callback is not passed. [#403](https://github.com/jprichardson/node-fs-extra/pull/403) - `pathExists()`, a replacement for the deprecated `fs.exists`. `pathExists` has a normal error-first callback signature. Also added `pathExistsSync`, an alias to `fs.existsSync`, for completeness. [#406](https://github.com/jprichardson/node-fs-extra/pull/406) ### Removed - **BREAKING:** Removed support for setting the default spaces for `writeJson()`, `writeJsonSync()`, `outputJson()`, & `outputJsonSync()`. This was undocumented. [#402](https://github.com/jprichardson/node-fs-extra/pull/402) ### Changed - Upgraded jsonfile dependency to v3.0.0: - **BREAKING:** Changed behavior of `throws` option for `readJsonSync()`; now does not throw filesystem errors when `throws` is `false`. - **BREAKING:** `writeJson()`, `writeJsonSync()`, `outputJson()`, & `outputJsonSync()` now output minified JSON by default for consistency with `JSON.stringify()`; set the `spaces` option to `2` to override this new behavior. [#402](https://github.com/jprichardson/node-fs-extra/pull/402) - Use `Buffer.allocUnsafe()` instead of `new Buffer()` in environments that support it. [#394](https://github.com/jprichardson/node-fs-extra/pull/394) ### Fixed - `removeSync()` silently failed on Windows in some cases. Now throws an `EBUSY` error. [#408](https://github.com/jprichardson/node-fs-extra/pull/408) 2.1.2 / 2017-03-16 ------------------ ### Fixed - Weird windows bug that resulted in `ensureDir()`'s callback being called twice in some cases. This bug may have also affected `remove()`. See [#392](https://github.com/jprichardson/node-fs-extra/issues/392), [#393](https://github.com/jprichardson/node-fs-extra/pull/393) 2.1.1 / 2017-03-15 ------------------ ### Fixed - Reverted [`5597bd`](https://github.com/jprichardson/node-fs-extra/commit/5597bd5b67f7d060f5f5bf26e9635be48330f5d7), this broke compatibility with Node.js versions v4+ but less than `v4.5.0`. - Remove `Buffer.alloc()` usage in `moveSync()`. 2.1.0 / 2017-03-15 ------------------ Thanks to [Mani Maghsoudlou (@manidlou)](https://github.com/manidlou) & [Jan Peer Stöcklmair (@JPeer264)](https://github.com/JPeer264) for their extraordinary help with this release! ### Added - `moveSync()` See [#309], [#381](https://github.com/jprichardson/node-fs-extra/pull/381). ([@manidlou](https://github.com/manidlou)) - `copy()` and `copySync()`'s `filter` option now gets the destination path passed as the second parameter. [#366](https://github.com/jprichardson/node-fs-extra/pull/366) ([@manidlou](https://github.com/manidlou)) ### Changed - Use `Buffer.alloc()` instead of deprecated `new Buffer()` in `copySync()`. [#380](https://github.com/jprichardson/node-fs-extra/pull/380) ([@manidlou](https://github.com/manidlou)) - Refactored entire codebase to use ES6 features supported by Node.js v4+ [#355](https://github.com/jprichardson/node-fs-extra/issues/355). [(@JPeer264)](https://github.com/JPeer264) - Refactored docs. ([@manidlou](https://github.com/manidlou)) ### Fixed - `move()` shouldn't error out when source and dest are the same. [#377](https://github.com/jprichardson/node-fs-extra/issues/377), [#378](https://github.com/jprichardson/node-fs-extra/pull/378) ([@jdalton](https://github.com/jdalton)) 2.0.0 / 2017-01-16 ------------------ ### Removed - **BREAKING:** Removed support for Node `v0.12`. The Node foundation stopped officially supporting it on Jan 1st, 2017. - **BREAKING:** Remove `walk()` and `walkSync()`. `walkSync()` was only part of `fs-extra` for a little over two months. Use [klaw](https://github.com/jprichardson/node-klaw) instead of `walk()`, in fact, `walk()` was just an alias to klaw. For `walkSync()` use [klaw-sync](https://github.com/mawni/node-klaw-sync). See: [#338], [#339] ### Changed - **BREAKING:** Renamed `clobber` to `overwrite`. This affects `copy()`, `copySync()`, and `move()`. [#330], [#333] - Moved docs, to `docs/`. [#340] ### Fixed - Apply filters to directories in `copySync()` like in `copy()`. [#324] - A specific condition when disk is under heavy use, `copy()` can fail. [#326] 1.0.0 / 2016-11-01 ------------------ After five years of development, we finally have reach the 1.0.0 milestone! Big thanks goes to [Ryan Zim](https://github.com/RyanZim) for leading the charge on this release! ### Added - `walkSync()` ### Changed - **BREAKING**: dropped Node v0.10 support. - disabled `rimaf` globbing, wasn't used. [#280] - deprecate `copy()/copySync()` option `filter` if it's a `RegExp`. `filter` should now be a function. - inline `rimraf`. This is temporary and was done because `rimraf` depended upon the beefy `glob` which `fs-extra` does not use. [#300] ### Fixed - bug fix proper closing of file handle on `utimesMillis()` [#271] - proper escaping of files with dollar signs [#291] - `copySync()` failed if user didn't own file. [#199], [#301] 0.30.0 / 2016-04-28 ------------------- - Brought back Node v0.10 support. I didn't realize there was still demand. Official support will end **2016-10-01**. 0.29.0 / 2016-04-27 ------------------- - **BREAKING**: removed support for Node v0.10. If you still want to use Node v0.10, everything should work except for `ensureLink()/ensureSymlink()`. Node v0.12 is still supported but will be dropped in the near future as well. 0.28.0 / 2016-04-17 ------------------- - **BREAKING**: removed `createOutputStream()`. Use https://www.npmjs.com/package/create-output-stream. See: [#192][#192] - `mkdirs()/mkdirsSync()` check for invalid win32 path chars. See: [#209][#209], [#237][#237] - `mkdirs()/mkdirsSync()` if drive not mounted, error. See: [#93][#93] 0.27.0 / 2016-04-15 ------------------- - add `dereference` option to `copySync()`. [#235][#235] 0.26.7 / 2016-03-16 ------------------- - fixed `copy()` if source and dest are the same. [#230][#230] 0.26.6 / 2016-03-15 ------------------- - fixed if `emptyDir()` does not have a callback: [#229][#229] 0.26.5 / 2016-01-27 ------------------- - `copy()` with two arguments (w/o callback) was broken. See: [#215][#215] 0.26.4 / 2016-01-05 ------------------- - `copySync()` made `preserveTimestamps` default consistent with `copy()` which is `false`. See: [#208][#208] 0.26.3 / 2015-12-17 ------------------- - fixed `copy()` hangup in copying blockDevice / characterDevice / `/dev/null`. See: [#193][#193] 0.26.2 / 2015-11-02 ------------------- - fixed `outputJson{Sync}()` spacing adherence to `fs.spaces` 0.26.1 / 2015-11-02 ------------------- - fixed `copySync()` when `clogger=true` and the destination is read only. See: [#190][#190] 0.26.0 / 2015-10-25 ------------------- - extracted the `walk()` function into its own module [`klaw`](https://github.com/jprichardson/node-klaw). 0.25.0 / 2015-10-24 ------------------- - now has a file walker `walk()` 0.24.0 / 2015-08-28 ------------------- - removed alias `delete()` and `deleteSync()`. See: [#171][#171] 0.23.1 / 2015-08-07 ------------------- - Better handling of errors for `move()` when moving across devices. [#170][#170] - `ensureSymlink()` and `ensureLink()` should not throw errors if link exists. [#169][#169] 0.23.0 / 2015-08-06 ------------------- - added `ensureLink{Sync}()` and `ensureSymlink{Sync}()`. See: [#165][#165] 0.22.1 / 2015-07-09 ------------------- - Prevent calling `hasMillisResSync()` on module load. See: [#149][#149]. Fixes regression that was introduced in `0.21.0`. 0.22.0 / 2015-07-09 ------------------- - preserve permissions / ownership in `copy()`. See: [#54][#54] 0.21.0 / 2015-07-04 ------------------- - add option to preserve timestamps in `copy()` and `copySync()`. See: [#141][#141] - updated `graceful-fs@3.x` to `4.x`. This brings in features from `amazing-graceful-fs` (much cleaner code / less hacks) 0.20.1 / 2015-06-23 ------------------- - fixed regression caused by latest jsonfile update: See: https://github.com/jprichardson/node-jsonfile/issues/26 0.20.0 / 2015-06-19 ------------------- - removed `jsonfile` aliases with `File` in the name, they weren't documented and probably weren't in use e.g. this package had both `fs.readJsonFile` and `fs.readJson` that were aliases to each other, now use `fs.readJson`. - preliminary walker created. Intentionally not documented. If you use it, it will almost certainly change and break your code. - started moving tests inline - upgraded to `jsonfile@2.1.0`, can now pass JSON revivers/replacers to `readJson()`, `writeJson()`, `outputJson()` 0.19.0 / 2015-06-08 ------------------- - `fs.copy()` had support for Node v0.8, dropped support 0.18.4 / 2015-05-22 ------------------- - fixed license field according to this: [#136][#136] and https://github.com/npm/npm/releases/tag/v2.10.0 0.18.3 / 2015-05-08 ------------------- - bugfix: handle `EEXIST` when clobbering on some Linux systems. [#134][#134] 0.18.2 / 2015-04-17 ------------------- - bugfix: allow `F_OK` ([#120][#120]) 0.18.1 / 2015-04-15 ------------------- - improved windows support for `move()` a bit. https://github.com/jprichardson/node-fs-extra/commit/92838980f25dc2ee4ec46b43ee14d3c4a1d30c1b - fixed a lot of tests for Windows (appveyor) 0.18.0 / 2015-03-31 ------------------- - added `emptyDir()` and `emptyDirSync()` 0.17.0 / 2015-03-28 ------------------- - `copySync` added `clobber` option (before always would clobber, now if `clobber` is `false` it throws an error if the destination exists). **Only works with files at the moment.** - `createOutputStream()` added. See: [#118][#118] 0.16.5 / 2015-03-08 ------------------- - fixed `fs.move` when `clobber` is `true` and destination is a directory, it should clobber. [#114][#114] 0.16.4 / 2015-03-01 ------------------- - `fs.mkdirs` fix infinite loop on Windows. See: See https://github.com/substack/node-mkdirp/pull/74 and https://github.com/substack/node-mkdirp/issues/66 0.16.3 / 2015-01-28 ------------------- - reverted https://github.com/jprichardson/node-fs-extra/commit/1ee77c8a805eba5b99382a2591ff99667847c9c9 0.16.2 / 2015-01-28 ------------------- - fixed `fs.copy` for Node v0.8 (support is temporary and will be removed in the near future) 0.16.1 / 2015-01-28 ------------------- - if `setImmediate` is not available, fall back to `process.nextTick` 0.16.0 / 2015-01-28 ------------------- - bugfix `fs.move()` into itself. Closes [#104] - bugfix `fs.move()` moving directory across device. Closes [#108] - added coveralls support - bugfix: nasty multiple callback `fs.copy()` bug. Closes [#98] - misc fs.copy code cleanups 0.15.0 / 2015-01-21 ------------------- - dropped `ncp`, imported code in - because of previous, now supports `io.js` - `graceful-fs` is now a dependency 0.14.0 / 2015-01-05 ------------------- - changed `copy`/`copySync` from `fs.copy(src, dest, [filters], callback)` to `fs.copy(src, dest, [options], callback)` [#100][#100] - removed mockfs tests for mkdirp (this may be temporary, but was getting in the way of other tests) 0.13.0 / 2014-12-10 ------------------- - removed `touch` and `touchSync` methods (they didn't handle permissions like UNIX touch) - updated `"ncp": "^0.6.0"` to `"ncp": "^1.0.1"` - imported `mkdirp` => `minimist` and `mkdirp` are no longer dependences, should now appease people who wanted `mkdirp` to be `--use_strict` safe. See [#59]([#59][#59]) 0.12.0 / 2014-09-22 ------------------- - copy symlinks in `copySync()` [#85][#85] 0.11.1 / 2014-09-02 ------------------- - bugfix `copySync()` preserve file permissions [#80][#80] 0.11.0 / 2014-08-11 ------------------- - upgraded `"ncp": "^0.5.1"` to `"ncp": "^0.6.0"` - upgrade `jsonfile": "^1.2.0"` to `jsonfile": "^2.0.0"` => on write, json files now have `\n` at end. Also adds `options.throws` to `readJsonSync()` see https://github.com/jprichardson/node-jsonfile#readfilesyncfilename-options for more details. 0.10.0 / 2014-06-29 ------------------ * bugfix: upgaded `"jsonfile": "~1.1.0"` to `"jsonfile": "^1.2.0"`, bumped minor because of `jsonfile` dep change from `~` to `^`. [#67] 0.9.1 / 2014-05-22 ------------------ * removed Node.js `0.8.x` support, `0.9.0` was published moments ago and should have been done there 0.9.0 / 2014-05-22 ------------------ * upgraded `ncp` from `~0.4.2` to `^0.5.1`, [#58] * upgraded `rimraf` from `~2.2.6` to `^2.2.8` * upgraded `mkdirp` from `0.3.x` to `^0.5.0` * added methods `ensureFile()`, `ensureFileSync()` * added methods `ensureDir()`, `ensureDirSync()` [#31] * added `move()` method. From: https://github.com/andrewrk/node-mv 0.8.1 / 2013-10-24 ------------------ * copy failed to return an error to the callback if a file doesn't exist (ulikoehler [#38], [#39]) 0.8.0 / 2013-10-14 ------------------ * `filter` implemented on `copy()` and `copySync()`. (Srirangan / [#36]) 0.7.1 / 2013-10-12 ------------------ * `copySync()` implemented (Srirangan / [#33]) * updated to the latest `jsonfile` version `1.1.0` which gives `options` params for the JSON methods. Closes [#32] 0.7.0 / 2013-10-07 ------------------ * update readme conventions * `copy()` now works if destination directory does not exist. Closes [#29] 0.6.4 / 2013-09-05 ------------------ * changed `homepage` field in package.json to remove NPM warning 0.6.3 / 2013-06-28 ------------------ * changed JSON spacing default from `4` to `2` to follow Node conventions * updated `jsonfile` dep * updated `rimraf` dep 0.6.2 / 2013-06-28 ------------------ * added .npmignore, [#25] 0.6.1 / 2013-05-14 ------------------ * modified for `strict` mode, closes [#24] * added `outputJson()/outputJsonSync()`, closes [#23] 0.6.0 / 2013-03-18 ------------------ * removed node 0.6 support * added node 0.10 support * upgraded to latest `ncp` and `rimraf`. * optional `graceful-fs` support. Closes [#17] 0.5.0 / 2013-02-03 ------------------ * Removed `readTextFile`. * Renamed `readJSONFile` to `readJSON` and `readJson`, same with write. * Restructured documentation a bit. Added roadmap. 0.4.0 / 2013-01-28 ------------------ * Set default spaces in `jsonfile` from 4 to 2. * Updated `testutil` deps for tests. * Renamed `touch()` to `createFile()` * Added `outputFile()` and `outputFileSync()` * Changed creation of testing diretories so the /tmp dir is not littered. * Added `readTextFile()` and `readTextFileSync()`. 0.3.2 / 2012-11-01 ------------------ * Added `touch()` and `touchSync()` methods. 0.3.1 / 2012-10-11 ------------------ * Fixed some stray globals. 0.3.0 / 2012-10-09 ------------------ * Removed all CoffeeScript from tests. * Renamed `mkdir` to `mkdirs`/`mkdirp`. 0.2.1 / 2012-09-11 ------------------ * Updated `rimraf` dep. 0.2.0 / 2012-09-10 ------------------ * Rewrote module into JavaScript. (Must still rewrite tests into JavaScript) * Added all methods of [jsonfile](https://github.com/jprichardson/node-jsonfile) * Added Travis-CI. 0.1.3 / 2012-08-13 ------------------ * Added method `readJSONFile`. 0.1.2 / 2012-06-15 ------------------ * Bug fix: `deleteSync()` didn't exist. * Verified Node v0.8 compatibility. 0.1.1 / 2012-06-15 ------------------ * Fixed bug in `remove()`/`delete()` that wouldn't execute the function if a callback wasn't passed. 0.1.0 / 2012-05-31 ------------------ * Renamed `copyFile()` to `copy()`. `copy()` can now copy directories (recursively) too. * Renamed `rmrf()` to `remove()`. * `remove()` aliased with `delete()`. * Added `mkdirp` capabilities. Named: `mkdir()`. Hides Node.js native `mkdir()`. * Instead of exporting the native `fs` module with new functions, I now copy over the native methods to a new object and export that instead. 0.0.4 / 2012-03-14 ------------------ * Removed CoffeeScript dependency 0.0.3 / 2012-01-11 ------------------ * Added methods rmrf and rmrfSync * Moved tests from Jasmine to Mocha [#344]: https://github.com/jprichardson/node-fs-extra/issues/344 "Licence Year" [#343]: https://github.com/jprichardson/node-fs-extra/pull/343 "Add klaw-sync link to readme" [#342]: https://github.com/jprichardson/node-fs-extra/pull/342 "allow preserveTimestamps when use move" [#341]: https://github.com/jprichardson/node-fs-extra/issues/341 "mkdirp(path.dirname(dest) in move() logic needs cleaning up [question]" [#340]: https://github.com/jprichardson/node-fs-extra/pull/340 "Move docs to seperate docs folder [documentation]" [#339]: https://github.com/jprichardson/node-fs-extra/pull/339 "Remove walk() & walkSync() [feature-walk]" [#338]: https://github.com/jprichardson/node-fs-extra/issues/338 "Remove walk() and walkSync() [feature-walk]" [#337]: https://github.com/jprichardson/node-fs-extra/issues/337 "copy doesn't return a yieldable value" [#336]: https://github.com/jprichardson/node-fs-extra/pull/336 "Docs enhanced walk sync [documentation, feature-walk]" [#335]: https://github.com/jprichardson/node-fs-extra/pull/335 "Refactor move() tests [feature-move]" [#334]: https://github.com/jprichardson/node-fs-extra/pull/334 "Cleanup lib/move/index.js [feature-move]" [#333]: https://github.com/jprichardson/node-fs-extra/pull/333 "Rename clobber to overwrite [feature-copy, feature-move]" [#332]: https://github.com/jprichardson/node-fs-extra/pull/332 "BREAKING: Drop Node v0.12 & io.js support" [#331]: https://github.com/jprichardson/node-fs-extra/issues/331 "Add support for chmodr [enhancement, future]" [#330]: https://github.com/jprichardson/node-fs-extra/pull/330 "BREAKING: Do not error when copy destination exists & clobber: false [feature-copy]" [#329]: https://github.com/jprichardson/node-fs-extra/issues/329 "Does .walk() scale to large directories? [question]" [#328]: https://github.com/jprichardson/node-fs-extra/issues/328 "Copying files corrupts [feature-copy, needs-confirmed]" [#327]: https://github.com/jprichardson/node-fs-extra/pull/327 "Use writeStream 'finish' event instead of 'close' [bug, feature-copy]" [#326]: https://github.com/jprichardson/node-fs-extra/issues/326 "fs.copy fails with chmod error when disk under heavy use [bug, feature-copy]" [#325]: https://github.com/jprichardson/node-fs-extra/issues/325 "ensureDir is difficult to promisify [enhancement]" [#324]: https://github.com/jprichardson/node-fs-extra/pull/324 "copySync() should apply filter to directories like copy() [bug, feature-copy]" [#323]: https://github.com/jprichardson/node-fs-extra/issues/323 "Support for `dest` being a directory when using `copy*()`?" [#322]: https://github.com/jprichardson/node-fs-extra/pull/322 "Add fs-promise as fs-extra-promise alternative" [#321]: https://github.com/jprichardson/node-fs-extra/issues/321 "fs.copy() with clobber set to false return EEXIST error [feature-copy]" [#320]: https://github.com/jprichardson/node-fs-extra/issues/320 "fs.copySync: Error: EPERM: operation not permitted, unlink " [#319]: https://github.com/jprichardson/node-fs-extra/issues/319 "Create directory if not exists" [#318]: https://github.com/jprichardson/node-fs-extra/issues/318 "Support glob patterns [enhancement, future]" [#317]: https://github.com/jprichardson/node-fs-extra/pull/317 "Adding copy sync test for src file without write perms" [#316]: https://github.com/jprichardson/node-fs-extra/pull/316 "Remove move()'s broken limit option [feature-move]" [#315]: https://github.com/jprichardson/node-fs-extra/pull/315 "Fix move clobber tests to work around graceful-fs bug." [#314]: https://github.com/jprichardson/node-fs-extra/issues/314 "move() limit option [documentation, enhancement, feature-move]" [#313]: https://github.com/jprichardson/node-fs-extra/pull/313 "Test that remove() ignores glob characters." [#312]: https://github.com/jprichardson/node-fs-extra/pull/312 "Enhance walkSync() to return items with path and stats [feature-walk]" [#311]: https://github.com/jprichardson/node-fs-extra/issues/311 "move() not work when dest name not provided [feature-move]" [#310]: https://github.com/jprichardson/node-fs-extra/issues/310 "Edit walkSync to return items like what walk emits [documentation, enhancement, feature-walk]" [#309]: https://github.com/jprichardson/node-fs-extra/issues/309 "moveSync support [enhancement, feature-move]" [#308]: https://github.com/jprichardson/node-fs-extra/pull/308 "Fix incorrect anchor link" [#307]: https://github.com/jprichardson/node-fs-extra/pull/307 "Fix coverage" [#306]: https://github.com/jprichardson/node-fs-extra/pull/306 "Update devDeps, fix lint error" [#305]: https://github.com/jprichardson/node-fs-extra/pull/305 "Re-add Coveralls" [#304]: https://github.com/jprichardson/node-fs-extra/pull/304 "Remove path-is-absolute [enhancement]" [#303]: https://github.com/jprichardson/node-fs-extra/pull/303 "Document copySync filter inconsistency [documentation, feature-copy]" [#302]: https://github.com/jprichardson/node-fs-extra/pull/302 "fix(console): depreciated -> deprecated" [#301]: https://github.com/jprichardson/node-fs-extra/pull/301 "Remove chmod call from copySync [feature-copy]" [#300]: https://github.com/jprichardson/node-fs-extra/pull/300 "Inline Rimraf [enhancement, feature-move, feature-remove]" [#299]: https://github.com/jprichardson/node-fs-extra/pull/299 "Warn when filter is a RegExp [feature-copy]" [#298]: https://github.com/jprichardson/node-fs-extra/issues/298 "API Docs [documentation]" [#297]: https://github.com/jprichardson/node-fs-extra/pull/297 "Warn about using preserveTimestamps on 32-bit node" [#296]: https://github.com/jprichardson/node-fs-extra/pull/296 "Improve EEXIST error message for copySync [enhancement]" [#295]: https://github.com/jprichardson/node-fs-extra/pull/295 "Depreciate using regular expressions for copy's filter option [documentation]" [#294]: https://github.com/jprichardson/node-fs-extra/pull/294 "BREAKING: Refactor lib/copy/ncp.js [feature-copy]" [#293]: https://github.com/jprichardson/node-fs-extra/pull/293 "Update CI configs" [#292]: https://github.com/jprichardson/node-fs-extra/issues/292 "Rewrite lib/copy/ncp.js [enhancement, feature-copy]" [#291]: https://github.com/jprichardson/node-fs-extra/pull/291 "Escape '$' in replacement string for async file copying" [#290]: https://github.com/jprichardson/node-fs-extra/issues/290 "Exclude files pattern while copying using copy.config.js [question]" [#289]: https://github.com/jprichardson/node-fs-extra/pull/289 "(Closes #271) lib/util/utimes: properly close file descriptors in the event of an error" [#288]: https://github.com/jprichardson/node-fs-extra/pull/288 "(Closes #271) lib/util/utimes: properly close file descriptors in the event of an error" [#287]: https://github.com/jprichardson/node-fs-extra/issues/287 "emptyDir() callback arguments are inconsistent [enhancement, feature-remove]" [#286]: https://github.com/jprichardson/node-fs-extra/pull/286 "Added walkSync function" [#285]: https://github.com/jprichardson/node-fs-extra/issues/285 "CITGM test failing on s390" [#284]: https://github.com/jprichardson/node-fs-extra/issues/284 "outputFile method is missing a check to determine if existing item is a folder or not" [#283]: https://github.com/jprichardson/node-fs-extra/pull/283 "Apply filter also on directories and symlinks for copySync()" [#282]: https://github.com/jprichardson/node-fs-extra/pull/282 "Apply filter also on directories and symlinks for copySync()" [#281]: https://github.com/jprichardson/node-fs-extra/issues/281 "remove function executes 'successfully' but doesn't do anything?" [#280]: https://github.com/jprichardson/node-fs-extra/pull/280 "Disable rimraf globbing" [#279]: https://github.com/jprichardson/node-fs-extra/issues/279 "Some code is vendored instead of included [awaiting-reply]" [#278]: https://github.com/jprichardson/node-fs-extra/issues/278 "copy() does not preserve file/directory ownership" [#277]: https://github.com/jprichardson/node-fs-extra/pull/277 "Mention defaults for clobber and dereference options" [#276]: https://github.com/jprichardson/node-fs-extra/issues/276 "Cannot connect to Shared Folder [awaiting-reply]" [#275]: https://github.com/jprichardson/node-fs-extra/issues/275 "EMFILE, too many open files on Mac OS with JSON API" [#274]: https://github.com/jprichardson/node-fs-extra/issues/274 "Use with memory-fs? [enhancement, future]" [#273]: https://github.com/jprichardson/node-fs-extra/pull/273 "tests: rename `remote.test.js` to `remove.test.js`" [#272]: https://github.com/jprichardson/node-fs-extra/issues/272 "Copy clobber flag never err even when true [bug, feature-copy]" [#271]: https://github.com/jprichardson/node-fs-extra/issues/271 "Unclosed file handle on futimes error" [#270]: https://github.com/jprichardson/node-fs-extra/issues/270 "copy not working as desired on Windows [feature-copy, platform-windows]" [#269]: https://github.com/jprichardson/node-fs-extra/issues/269 "Copying with preserveTimeStamps: true is inaccurate using 32bit node [feature-copy]" [#268]: https://github.com/jprichardson/node-fs-extra/pull/268 "port fix for mkdirp issue #111" [#267]: https://github.com/jprichardson/node-fs-extra/issues/267 "WARN deprecated wrench@1.5.9: wrench.js is deprecated!" [#266]: https://github.com/jprichardson/node-fs-extra/issues/266 "fs-extra" [#265]: https://github.com/jprichardson/node-fs-extra/issues/265 "Link the `fs.stat fs.exists` etc. methods for replace the `fs` module forever?" [#264]: https://github.com/jprichardson/node-fs-extra/issues/264 "Renaming a file using move fails when a file inside is open (at least on windows) [wont-fix]" [#263]: https://github.com/jprichardson/node-fs-extra/issues/263 "ENOSYS: function not implemented, link [needs-confirmed]" [#262]: https://github.com/jprichardson/node-fs-extra/issues/262 "Add .exists() and .existsSync()" [#261]: https://github.com/jprichardson/node-fs-extra/issues/261 "Cannot read property 'prototype' of undefined" [#260]: https://github.com/jprichardson/node-fs-extra/pull/260 "use more specific path for method require" [#259]: https://github.com/jprichardson/node-fs-extra/issues/259 "Feature Request: isEmpty" [#258]: https://github.com/jprichardson/node-fs-extra/issues/258 "copy files does not preserve file timestamp" [#257]: https://github.com/jprichardson/node-fs-extra/issues/257 "Copying a file on windows fails" [#256]: https://github.com/jprichardson/node-fs-extra/pull/256 "Updated Readme " [#255]: https://github.com/jprichardson/node-fs-extra/issues/255 "Update rimraf required version" [#254]: https://github.com/jprichardson/node-fs-extra/issues/254 "request for readTree, readTreeSync, walkSync method" [#253]: https://github.com/jprichardson/node-fs-extra/issues/253 "outputFile does not touch mtime when file exists" [#252]: https://github.com/jprichardson/node-fs-extra/pull/252 "Fixing problem when copying file with no write permission" [#251]: https://github.com/jprichardson/node-fs-extra/issues/251 "Just wanted to say thank you" [#250]: https://github.com/jprichardson/node-fs-extra/issues/250 "`fs.remove()` not removing files (works with `rm -rf`)" [#249]: https://github.com/jprichardson/node-fs-extra/issues/249 "Just a Question ... Remove Servers" [#248]: https://github.com/jprichardson/node-fs-extra/issues/248 "Allow option to not preserve permissions for copy" [#247]: https://github.com/jprichardson/node-fs-extra/issues/247 "Add TypeScript typing directly in the fs-extra package" [#246]: https://github.com/jprichardson/node-fs-extra/issues/246 "fse.remove() && fse.removeSync() don't throw error on ENOENT file" [#245]: https://github.com/jprichardson/node-fs-extra/issues/245 "filter for empty dir [enhancement]" [#244]: https://github.com/jprichardson/node-fs-extra/issues/244 "copySync doesn't apply the filter to directories" [#243]: https://github.com/jprichardson/node-fs-extra/issues/243 "Can I request fs.walk() to be synchronous?" [#242]: https://github.com/jprichardson/node-fs-extra/issues/242 "Accidentally truncates file names ending with $$ [bug, feature-copy]" [#241]: https://github.com/jprichardson/node-fs-extra/pull/241 "Remove link to createOutputStream" [#240]: https://github.com/jprichardson/node-fs-extra/issues/240 "walkSync request" [#239]: https://github.com/jprichardson/node-fs-extra/issues/239 "Depreciate regular expressions for copy's filter [documentation, feature-copy]" [#238]: https://github.com/jprichardson/node-fs-extra/issues/238 "Can't write to files while in a worker thread." [#237]: https://github.com/jprichardson/node-fs-extra/issues/237 ".ensureDir(..) fails silently when passed an invalid path..." [#236]: https://github.com/jprichardson/node-fs-extra/issues/236 "[Removed] Filed under wrong repo" [#235]: https://github.com/jprichardson/node-fs-extra/pull/235 "Adds symlink dereference option to `fse.copySync` (#191)" [#234]: https://github.com/jprichardson/node-fs-extra/issues/234 "ensureDirSync fails silent when EACCES: permission denied on travis-ci" [#233]: https://github.com/jprichardson/node-fs-extra/issues/233 "please make sure the first argument in callback is error object [feature-copy]" [#232]: https://github.com/jprichardson/node-fs-extra/issues/232 "Copy a folder content to its child folder. " [#231]: https://github.com/jprichardson/node-fs-extra/issues/231 "Adding read/write/output functions for YAML" [#230]: https://github.com/jprichardson/node-fs-extra/pull/230 "throw error if src and dest are the same to avoid zeroing out + test" [#229]: https://github.com/jprichardson/node-fs-extra/pull/229 "fix 'TypeError: callback is not a function' in emptyDir" [#228]: https://github.com/jprichardson/node-fs-extra/pull/228 "Throw error when target is empty so file is not accidentally zeroed out" [#227]: https://github.com/jprichardson/node-fs-extra/issues/227 "Uncatchable errors when there are invalid arguments [feature-move]" [#226]: https://github.com/jprichardson/node-fs-extra/issues/226 "Moving to the current directory" [#225]: https://github.com/jprichardson/node-fs-extra/issues/225 "EBUSY: resource busy or locked, unlink" [#224]: https://github.com/jprichardson/node-fs-extra/issues/224 "fse.copy ENOENT error" [#223]: https://github.com/jprichardson/node-fs-extra/issues/223 "Suspicious behavior of fs.existsSync" [#222]: https://github.com/jprichardson/node-fs-extra/pull/222 "A clearer description of emtpyDir function" [#221]: https://github.com/jprichardson/node-fs-extra/pull/221 "Update README.md" [#220]: https://github.com/jprichardson/node-fs-extra/pull/220 "Non-breaking feature: add option 'passStats' to copy methods." [#219]: https://github.com/jprichardson/node-fs-extra/pull/219 "Add closing parenthesis in copySync example" [#218]: https://github.com/jprichardson/node-fs-extra/pull/218 "fix #187 #70 options.filter bug" [#217]: https://github.com/jprichardson/node-fs-extra/pull/217 "fix #187 #70 options.filter bug" [#216]: https://github.com/jprichardson/node-fs-extra/pull/216 "fix #187 #70 options.filter bug" [#215]: https://github.com/jprichardson/node-fs-extra/pull/215 "fse.copy throws error when only src and dest provided [bug, documentation, feature-copy]" [#214]: https://github.com/jprichardson/node-fs-extra/pull/214 "Fixing copySync anchor tag" [#213]: https://github.com/jprichardson/node-fs-extra/issues/213 "Merge extfs with this repo" [#212]: https://github.com/jprichardson/node-fs-extra/pull/212 "Update year to 2016 in README.md and LICENSE" [#211]: https://github.com/jprichardson/node-fs-extra/issues/211 "Not copying all files" [#210]: https://github.com/jprichardson/node-fs-extra/issues/210 "copy/copySync behave differently when copying a symbolic file [bug, documentation, feature-copy]" [#209]: https://github.com/jprichardson/node-fs-extra/issues/209 "In Windows invalid directory name causes infinite loop in ensureDir(). [bug]" [#208]: https://github.com/jprichardson/node-fs-extra/pull/208 "fix options.preserveTimestamps to false in copy-sync by default [feature-copy]" [#207]: https://github.com/jprichardson/node-fs-extra/issues/207 "Add `compare` suite of functions" [#206]: https://github.com/jprichardson/node-fs-extra/issues/206 "outputFileSync" [#205]: https://github.com/jprichardson/node-fs-extra/issues/205 "fix documents about copy/copySync [documentation, feature-copy]" [#204]: https://github.com/jprichardson/node-fs-extra/pull/204 "allow copy of block and character device files" [#203]: https://github.com/jprichardson/node-fs-extra/issues/203 "copy method's argument options couldn't be undefined [bug, feature-copy]" [#202]: https://github.com/jprichardson/node-fs-extra/issues/202 "why there is not a walkSync method?" [#201]: https://github.com/jprichardson/node-fs-extra/issues/201 "clobber for directories [feature-copy, future]" [#200]: https://github.com/jprichardson/node-fs-extra/issues/200 "'copySync' doesn't work in sync" [#199]: https://github.com/jprichardson/node-fs-extra/issues/199 "fs.copySync fails if user does not own file [bug, feature-copy]" [#198]: https://github.com/jprichardson/node-fs-extra/issues/198 "handle copying between identical files [feature-copy]" [#197]: https://github.com/jprichardson/node-fs-extra/issues/197 "Missing documentation for `outputFile` `options` 3rd parameter [documentation]" [#196]: https://github.com/jprichardson/node-fs-extra/issues/196 "copy filter: async function and/or function called with `fs.stat` result [future]" [#195]: https://github.com/jprichardson/node-fs-extra/issues/195 "How to override with outputFile?" [#194]: https://github.com/jprichardson/node-fs-extra/pull/194 "allow ensureFile(Sync) to provide data to be written to created file" [#193]: https://github.com/jprichardson/node-fs-extra/issues/193 "`fs.copy` fails silently if source file is /dev/null [bug, feature-copy]" [#192]: https://github.com/jprichardson/node-fs-extra/issues/192 "Remove fs.createOutputStream()" [#191]: https://github.com/jprichardson/node-fs-extra/issues/191 "How to copy symlinks to target as normal folders [feature-copy]" [#190]: https://github.com/jprichardson/node-fs-extra/pull/190 "copySync to overwrite destination file if readonly and clobber true" [#189]: https://github.com/jprichardson/node-fs-extra/pull/189 "move.test fix to support CRLF on Windows" [#188]: https://github.com/jprichardson/node-fs-extra/issues/188 "move.test failing on windows platform" [#187]: https://github.com/jprichardson/node-fs-extra/issues/187 "Not filter each file, stops on first false [feature-copy]" [#186]: https://github.com/jprichardson/node-fs-extra/issues/186 "Do you need a .size() function in this module? [future]" [#185]: https://github.com/jprichardson/node-fs-extra/issues/185 "Doesn't work on NodeJS v4.x" [#184]: https://github.com/jprichardson/node-fs-extra/issues/184 "CLI equivalent for fs-extra" [#183]: https://github.com/jprichardson/node-fs-extra/issues/183 "with clobber true, copy and copySync behave differently if destination file is read only [bug, feature-copy]" [#182]: https://github.com/jprichardson/node-fs-extra/issues/182 "ensureDir(dir, callback) second callback parameter not specified" [#181]: https://github.com/jprichardson/node-fs-extra/issues/181 "Add ability to remove file securely [enhancement, wont-fix]" [#180]: https://github.com/jprichardson/node-fs-extra/issues/180 "Filter option doesn't work the same way in copy and copySync [bug, feature-copy]" [#179]: https://github.com/jprichardson/node-fs-extra/issues/179 "Include opendir" [#178]: https://github.com/jprichardson/node-fs-extra/issues/178 "ENOTEMPTY is thrown on removeSync " [#177]: https://github.com/jprichardson/node-fs-extra/issues/177 "fix `remove()` wildcards (introduced by rimraf) [feature-remove]" [#176]: https://github.com/jprichardson/node-fs-extra/issues/176 "createOutputStream doesn't emit 'end' event" [#175]: https://github.com/jprichardson/node-fs-extra/issues/175 "[Feature Request].moveSync support [feature-move, future]" [#174]: https://github.com/jprichardson/node-fs-extra/pull/174 "Fix copy formatting and document options.filter" [#173]: https://github.com/jprichardson/node-fs-extra/issues/173 "Feature Request: writeJson should mkdirs" [#172]: https://github.com/jprichardson/node-fs-extra/issues/172 "rename `clobber` flags to `overwrite`" [#171]: https://github.com/jprichardson/node-fs-extra/issues/171 "remove unnecessary aliases" [#170]: https://github.com/jprichardson/node-fs-extra/pull/170 "More robust handling of errors moving across virtual drives" [#169]: https://github.com/jprichardson/node-fs-extra/pull/169 "suppress ensureLink & ensureSymlink dest exists error" [#168]: https://github.com/jprichardson/node-fs-extra/pull/168 "suppress ensurelink dest exists error" [#167]: https://github.com/jprichardson/node-fs-extra/pull/167 "Adds basic (string, buffer) support for ensureFile content [future]" [#166]: https://github.com/jprichardson/node-fs-extra/pull/166 "Adds basic (string, buffer) support for ensureFile content" [#165]: https://github.com/jprichardson/node-fs-extra/pull/165 "ensure for link & symlink" [#164]: https://github.com/jprichardson/node-fs-extra/issues/164 "Feature Request: ensureFile to take optional argument for file content" [#163]: https://github.com/jprichardson/node-fs-extra/issues/163 "ouputJson not formatted out of the box [bug]" [#162]: https://github.com/jprichardson/node-fs-extra/pull/162 "ensure symlink & link" [#161]: https://github.com/jprichardson/node-fs-extra/pull/161 "ensure symlink & link" [#160]: https://github.com/jprichardson/node-fs-extra/pull/160 "ensure symlink & link" [#159]: https://github.com/jprichardson/node-fs-extra/pull/159 "ensure symlink & link" [#158]: https://github.com/jprichardson/node-fs-extra/issues/158 "Feature Request: ensureLink and ensureSymlink methods" [#157]: https://github.com/jprichardson/node-fs-extra/issues/157 "writeJson isn't formatted" [#156]: https://github.com/jprichardson/node-fs-extra/issues/156 "Promise.promisifyAll doesn't work for some methods" [#155]: https://github.com/jprichardson/node-fs-extra/issues/155 "Readme" [#154]: https://github.com/jprichardson/node-fs-extra/issues/154 "/tmp/millis-test-sync" [#153]: https://github.com/jprichardson/node-fs-extra/pull/153 "Make preserveTimes also work on read-only files. Closes #152" [#152]: https://github.com/jprichardson/node-fs-extra/issues/152 "fs.copy fails for read-only files with preserveTimestamp=true [feature-copy]" [#151]: https://github.com/jprichardson/node-fs-extra/issues/151 "TOC does not work correctly on npm [documentation]" [#150]: https://github.com/jprichardson/node-fs-extra/issues/150 "Remove test file fixtures, create with code." [#149]: https://github.com/jprichardson/node-fs-extra/issues/149 "/tmp/millis-test-sync" [#148]: https://github.com/jprichardson/node-fs-extra/issues/148 "split out `Sync` methods in documentation" [#147]: https://github.com/jprichardson/node-fs-extra/issues/147 "Adding rmdirIfEmpty" [#146]: https://github.com/jprichardson/node-fs-extra/pull/146 "ensure test.js works" [#145]: https://github.com/jprichardson/node-fs-extra/issues/145 "Add `fs.exists` and `fs.existsSync` if it doesn't exist." [#144]: https://github.com/jprichardson/node-fs-extra/issues/144 "tests failing" [#143]: https://github.com/jprichardson/node-fs-extra/issues/143 "update graceful-fs" [#142]: https://github.com/jprichardson/node-fs-extra/issues/142 "PrependFile Feature" [#141]: https://github.com/jprichardson/node-fs-extra/pull/141 "Add option to preserve timestamps" [#140]: https://github.com/jprichardson/node-fs-extra/issues/140 "Json file reading fails with 'utf8'" [#139]: https://github.com/jprichardson/node-fs-extra/pull/139 "Preserve file timestamp on copy. Closes #138" [#138]: https://github.com/jprichardson/node-fs-extra/issues/138 "Preserve timestamps on copying files" [#137]: https://github.com/jprichardson/node-fs-extra/issues/137 "outputFile/outputJson: Unexpected end of input" [#136]: https://github.com/jprichardson/node-fs-extra/pull/136 "Update license attribute" [#135]: https://github.com/jprichardson/node-fs-extra/issues/135 "emptyDir throws Error if no callback is provided" [#134]: https://github.com/jprichardson/node-fs-extra/pull/134 "Handle EEXIST error when clobbering dir" [#133]: https://github.com/jprichardson/node-fs-extra/pull/133 "Travis runs with `sudo: false`" [#132]: https://github.com/jprichardson/node-fs-extra/pull/132 "isDirectory method" [#131]: https://github.com/jprichardson/node-fs-extra/issues/131 "copySync is not working iojs 1.8.4 on linux [feature-copy]" [#130]: https://github.com/jprichardson/node-fs-extra/pull/130 "Please review additional features." [#129]: https://github.com/jprichardson/node-fs-extra/pull/129 "can you review this feature?" [#128]: https://github.com/jprichardson/node-fs-extra/issues/128 "fsExtra.move(filepath, newPath) broken;" [#127]: https://github.com/jprichardson/node-fs-extra/issues/127 "consider using fs.access to remove deprecated warnings for fs.exists" [#126]: https://github.com/jprichardson/node-fs-extra/issues/126 " TypeError: Object # has no method 'access'" [#125]: https://github.com/jprichardson/node-fs-extra/issues/125 "Question: What do the *Sync function do different from non-sync" [#124]: https://github.com/jprichardson/node-fs-extra/issues/124 "move with clobber option 'ENOTEMPTY'" [#123]: https://github.com/jprichardson/node-fs-extra/issues/123 "Only copy the content of a directory" [#122]: https://github.com/jprichardson/node-fs-extra/pull/122 "Update section links in README to match current section ids." [#121]: https://github.com/jprichardson/node-fs-extra/issues/121 "emptyDir is undefined" [#120]: https://github.com/jprichardson/node-fs-extra/issues/120 "usage bug caused by shallow cloning methods of 'graceful-fs'" [#119]: https://github.com/jprichardson/node-fs-extra/issues/119 "mkdirs and ensureDir never invoke callback and consume CPU indefinitely if provided a path with invalid characters on Windows" [#118]: https://github.com/jprichardson/node-fs-extra/pull/118 "createOutputStream" [#117]: https://github.com/jprichardson/node-fs-extra/pull/117 "Fixed issue with slash separated paths on windows" [#116]: https://github.com/jprichardson/node-fs-extra/issues/116 "copySync can only copy directories not files [documentation, feature-copy]" [#115]: https://github.com/jprichardson/node-fs-extra/issues/115 ".Copy & .CopySync [feature-copy]" [#114]: https://github.com/jprichardson/node-fs-extra/issues/114 "Fails to move (rename) directory to non-empty directory even with clobber: true" [#113]: https://github.com/jprichardson/node-fs-extra/issues/113 "fs.copy seems to callback early if the destination file already exists" [#112]: https://github.com/jprichardson/node-fs-extra/pull/112 "Copying a file into an existing directory" [#111]: https://github.com/jprichardson/node-fs-extra/pull/111 "Moving a file into an existing directory " [#110]: https://github.com/jprichardson/node-fs-extra/pull/110 "Moving a file into an existing directory" [#109]: https://github.com/jprichardson/node-fs-extra/issues/109 "fs.move across windows drives fails" [#108]: https://github.com/jprichardson/node-fs-extra/issues/108 "fse.move directories across multiple devices doesn't work" [#107]: https://github.com/jprichardson/node-fs-extra/pull/107 "Check if dest path is an existing dir and copy or move source in it" [#106]: https://github.com/jprichardson/node-fs-extra/issues/106 "fse.copySync crashes while copying across devices D: [feature-copy]" [#105]: https://github.com/jprichardson/node-fs-extra/issues/105 "fs.copy hangs on iojs" [#104]: https://github.com/jprichardson/node-fs-extra/issues/104 "fse.move deletes folders [bug]" [#103]: https://github.com/jprichardson/node-fs-extra/issues/103 "Error: EMFILE with copy" [#102]: https://github.com/jprichardson/node-fs-extra/issues/102 "touch / touchSync was removed ?" [#101]: https://github.com/jprichardson/node-fs-extra/issues/101 "fs-extra promisified" [#100]: https://github.com/jprichardson/node-fs-extra/pull/100 "copy: options object or filter to pass to ncp" [#99]: https://github.com/jprichardson/node-fs-extra/issues/99 "ensureDir() modes [future]" [#98]: https://github.com/jprichardson/node-fs-extra/issues/98 "fs.copy() incorrect async behavior [bug]" [#97]: https://github.com/jprichardson/node-fs-extra/pull/97 "use path.join; fix copySync bug" [#96]: https://github.com/jprichardson/node-fs-extra/issues/96 "destFolderExists in copySync is always undefined." [#95]: https://github.com/jprichardson/node-fs-extra/pull/95 "Using graceful-ncp instead of ncp" [#94]: https://github.com/jprichardson/node-fs-extra/issues/94 "Error: EEXIST, file already exists '../mkdirp/bin/cmd.js' on fs.copySync() [enhancement, feature-copy]" [#93]: https://github.com/jprichardson/node-fs-extra/issues/93 "Confusing error if drive not mounted [enhancement]" [#92]: https://github.com/jprichardson/node-fs-extra/issues/92 "Problems with Bluebird" [#91]: https://github.com/jprichardson/node-fs-extra/issues/91 "fs.copySync('/test', '/haha') is different with 'cp -r /test /haha' [enhancement]" [#90]: https://github.com/jprichardson/node-fs-extra/issues/90 "Folder creation and file copy is Happening in 64 bit machine but not in 32 bit machine" [#89]: https://github.com/jprichardson/node-fs-extra/issues/89 "Error: EEXIST using fs-extra's fs.copy to copy a directory on Windows" [#88]: https://github.com/jprichardson/node-fs-extra/issues/88 "Stacking those libraries" [#87]: https://github.com/jprichardson/node-fs-extra/issues/87 "createWriteStream + outputFile = ?" [#86]: https://github.com/jprichardson/node-fs-extra/issues/86 "no moveSync?" [#85]: https://github.com/jprichardson/node-fs-extra/pull/85 "Copy symlinks in copySync" [#84]: https://github.com/jprichardson/node-fs-extra/issues/84 "Push latest version to npm ?" [#83]: https://github.com/jprichardson/node-fs-extra/issues/83 "Prevent copying a directory into itself [feature-copy]" [#82]: https://github.com/jprichardson/node-fs-extra/pull/82 "README updates for move" [#81]: https://github.com/jprichardson/node-fs-extra/issues/81 "fd leak after fs.move" [#80]: https://github.com/jprichardson/node-fs-extra/pull/80 "Preserve file mode in copySync" [#79]: https://github.com/jprichardson/node-fs-extra/issues/79 "fs.copy only .html file empty" [#78]: https://github.com/jprichardson/node-fs-extra/pull/78 "copySync was not applying filters to directories" [#77]: https://github.com/jprichardson/node-fs-extra/issues/77 "Create README reference to bluebird" [#76]: https://github.com/jprichardson/node-fs-extra/issues/76 "Create README reference to typescript" [#75]: https://github.com/jprichardson/node-fs-extra/issues/75 "add glob as a dep? [question]" [#74]: https://github.com/jprichardson/node-fs-extra/pull/74 "including new emptydir module" [#73]: https://github.com/jprichardson/node-fs-extra/pull/73 "add dependency status in readme" [#72]: https://github.com/jprichardson/node-fs-extra/pull/72 "Use svg instead of png to get better image quality" [#71]: https://github.com/jprichardson/node-fs-extra/issues/71 "fse.copy not working on Windows 7 x64 OS, but, copySync does work" [#70]: https://github.com/jprichardson/node-fs-extra/issues/70 "Not filter each file, stops on first false [bug]" [#69]: https://github.com/jprichardson/node-fs-extra/issues/69 "How to check if folder exist and read the folder name" [#68]: https://github.com/jprichardson/node-fs-extra/issues/68 "consider flag to readJsonSync (throw false) [enhancement]" [#67]: https://github.com/jprichardson/node-fs-extra/issues/67 "docs for readJson incorrectly states that is accepts options" [#66]: https://github.com/jprichardson/node-fs-extra/issues/66 "ENAMETOOLONG" [#65]: https://github.com/jprichardson/node-fs-extra/issues/65 "exclude filter in fs.copy" [#64]: https://github.com/jprichardson/node-fs-extra/issues/64 "Announce: mfs - monitor your fs-extra calls" [#63]: https://github.com/jprichardson/node-fs-extra/issues/63 "Walk" [#62]: https://github.com/jprichardson/node-fs-extra/issues/62 "npm install fs-extra doesn't work" [#61]: https://github.com/jprichardson/node-fs-extra/issues/61 "No longer supports node 0.8 due to use of `^` in package.json dependencies" [#60]: https://github.com/jprichardson/node-fs-extra/issues/60 "chmod & chown for mkdirs" [#59]: https://github.com/jprichardson/node-fs-extra/issues/59 "Consider including mkdirp and making fs-extra '--use_strict' safe [question]" [#58]: https://github.com/jprichardson/node-fs-extra/issues/58 "Stack trace not included in fs.copy error" [#57]: https://github.com/jprichardson/node-fs-extra/issues/57 "Possible to include wildcards in delete?" [#56]: https://github.com/jprichardson/node-fs-extra/issues/56 "Crash when have no access to write to destination file in copy " [#55]: https://github.com/jprichardson/node-fs-extra/issues/55 "Is it possible to have any console output similar to Grunt copy module?" [#54]: https://github.com/jprichardson/node-fs-extra/issues/54 "`copy` does not preserve file ownership and permissons" [#53]: https://github.com/jprichardson/node-fs-extra/issues/53 "outputFile() - ability to write data in appending mode" [#52]: https://github.com/jprichardson/node-fs-extra/pull/52 "This fixes (what I think) is a bug in copySync" [#51]: https://github.com/jprichardson/node-fs-extra/pull/51 "Add a Bitdeli Badge to README" [#50]: https://github.com/jprichardson/node-fs-extra/issues/50 "Replace mechanism in createFile" [#49]: https://github.com/jprichardson/node-fs-extra/pull/49 "update rimraf to v2.2.6" [#48]: https://github.com/jprichardson/node-fs-extra/issues/48 "fs.copy issue [bug]" [#47]: https://github.com/jprichardson/node-fs-extra/issues/47 "Bug in copy - callback called on readStream 'close' - Fixed in ncp 0.5.0" [#46]: https://github.com/jprichardson/node-fs-extra/pull/46 "update copyright year" [#45]: https://github.com/jprichardson/node-fs-extra/pull/45 "Added note about fse.outputFile() being the one that overwrites" [#44]: https://github.com/jprichardson/node-fs-extra/pull/44 "Proposal: Stream support" [#43]: https://github.com/jprichardson/node-fs-extra/issues/43 "Better error reporting " [#42]: https://github.com/jprichardson/node-fs-extra/issues/42 "Performance issue?" [#41]: https://github.com/jprichardson/node-fs-extra/pull/41 "There does seem to be a synchronous version now" [#40]: https://github.com/jprichardson/node-fs-extra/issues/40 "fs.copy throw unexplained error ENOENT, utime " [#39]: https://github.com/jprichardson/node-fs-extra/pull/39 "Added regression test for copy() return callback on error" [#38]: https://github.com/jprichardson/node-fs-extra/pull/38 "Return err in copy() fstat cb, because stat could be undefined or null" [#37]: https://github.com/jprichardson/node-fs-extra/issues/37 "Maybe include a line reader? [enhancement, question]" [#36]: https://github.com/jprichardson/node-fs-extra/pull/36 "`filter` parameter `fs.copy` and `fs.copySync`" [#35]: https://github.com/jprichardson/node-fs-extra/pull/35 "`filter` parameter `fs.copy` and `fs.copySync` " [#34]: https://github.com/jprichardson/node-fs-extra/issues/34 "update docs to include options for JSON methods [enhancement]" [#33]: https://github.com/jprichardson/node-fs-extra/pull/33 "fs_extra.copySync" [#32]: https://github.com/jprichardson/node-fs-extra/issues/32 "update to latest jsonfile [enhancement]" [#31]: https://github.com/jprichardson/node-fs-extra/issues/31 "Add ensure methods [enhancement]" [#30]: https://github.com/jprichardson/node-fs-extra/issues/30 "update package.json optional dep `graceful-fs`" [#29]: https://github.com/jprichardson/node-fs-extra/issues/29 "Copy failing if dest directory doesn't exist. Is this intended?" [#28]: https://github.com/jprichardson/node-fs-extra/issues/28 "homepage field must be a string url. Deleted." [#27]: https://github.com/jprichardson/node-fs-extra/issues/27 "Update Readme" [#26]: https://github.com/jprichardson/node-fs-extra/issues/26 "Add readdir recursive method. [enhancement]" [#25]: https://github.com/jprichardson/node-fs-extra/pull/25 "adding an `.npmignore` file" [#24]: https://github.com/jprichardson/node-fs-extra/issues/24 "[bug] cannot run in strict mode [bug]" [#23]: https://github.com/jprichardson/node-fs-extra/issues/23 "`writeJSON()` should create parent directories" [#22]: https://github.com/jprichardson/node-fs-extra/pull/22 "Add a limit option to mkdirs()" [#21]: https://github.com/jprichardson/node-fs-extra/issues/21 "touch() in 0.10.0" [#20]: https://github.com/jprichardson/node-fs-extra/issues/20 "fs.remove yields callback before directory is really deleted" [#19]: https://github.com/jprichardson/node-fs-extra/issues/19 "fs.copy err is empty array" [#18]: https://github.com/jprichardson/node-fs-extra/pull/18 "Exposed copyFile Function" [#17]: https://github.com/jprichardson/node-fs-extra/issues/17 "Use `require('graceful-fs')` if found instead of `require('fs')`" [#16]: https://github.com/jprichardson/node-fs-extra/pull/16 "Update README.md" [#15]: https://github.com/jprichardson/node-fs-extra/issues/15 "Implement cp -r but sync aka copySync. [enhancement]" [#14]: https://github.com/jprichardson/node-fs-extra/issues/14 "fs.mkdirSync is broken in 0.3.1" [#13]: https://github.com/jprichardson/node-fs-extra/issues/13 "Thoughts on including a directory tree / file watcher? [enhancement, question]" [#12]: https://github.com/jprichardson/node-fs-extra/issues/12 "copyFile & copyFileSync are global" [#11]: https://github.com/jprichardson/node-fs-extra/issues/11 "Thoughts on including a file walker? [enhancement, question]" [#10]: https://github.com/jprichardson/node-fs-extra/issues/10 "move / moveFile API [enhancement]" [#9]: https://github.com/jprichardson/node-fs-extra/issues/9 "don't import normal fs stuff into fs-extra" [#8]: https://github.com/jprichardson/node-fs-extra/pull/8 "Update rimraf to latest version" [#6]: https://github.com/jprichardson/node-fs-extra/issues/6 "Remove CoffeeScript development dependency" [#5]: https://github.com/jprichardson/node-fs-extra/issues/5 "comments on naming" [#4]: https://github.com/jprichardson/node-fs-extra/issues/4 "version bump to 0.2" [#3]: https://github.com/jprichardson/node-fs-extra/pull/3 "Hi! I fixed some code for you!" [#2]: https://github.com/jprichardson/node-fs-extra/issues/2 "Merge with fs.extra and mkdirp" [#1]: https://github.com/jprichardson/node-fs-extra/issues/1 "file-extra npm !exist" ================================================ FILE: LICENSE ================================================ (The MIT License) Copyright (c) 2011-2024 JP Richardson Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: README.md ================================================ Node.js: fs-extra ================= `fs-extra` adds file system methods that aren't included in the native `fs` module and adds promise support to the `fs` methods. It also uses [`graceful-fs`](https://github.com/isaacs/node-graceful-fs) to prevent `EMFILE` errors. It should be a drop in replacement for `fs`. [![npm Package](https://img.shields.io/npm/v/fs-extra.svg)](https://www.npmjs.org/package/fs-extra) [![License](https://img.shields.io/npm/l/fs-extra.svg)](https://github.com/jprichardson/node-fs-extra/blob/master/LICENSE) [![build status](https://img.shields.io/github/actions/workflow/status/jprichardson/node-fs-extra/ci.yml?branch=master)](https://github.com/jprichardson/node-fs-extra/actions/workflows/ci.yml?query=branch%3Amaster) [![downloads per month](http://img.shields.io/npm/dm/fs-extra.svg)](https://www.npmjs.org/package/fs-extra) [![JavaScript Style Guide](https://img.shields.io/badge/code_style-standard-brightgreen.svg)](https://standardjs.com) Why? ---- I got tired of including `mkdirp`, `rimraf`, and `ncp` in most of my projects. Installation ------------ npm install fs-extra Usage ----- ### CommonJS `fs-extra` is a drop in replacement for native `fs`. All methods in `fs` are attached to `fs-extra`. All `fs` methods return promises if the callback isn't passed. You don't ever need to include the original `fs` module again: ```js const fs = require('fs') // this is no longer necessary ``` you can now do this: ```js const 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: ```js const fse = require('fs-extra') ``` you can also keep both, but it's redundant: ```js const fs = require('fs') const fse = require('fs-extra') ``` **NOTE:** The deprecated constants `fs.F_OK`, `fs.R_OK`, `fs.W_OK`, & `fs.X_OK` are not exported on Node.js v24.0.0+; please use their `fs.constants` equivalents. ### ESM There is also an `fs-extra/esm` import, that supports both default and named exports. However, note that `fs` methods are not included in `fs-extra/esm`; you still need to import `fs` and/or `fs/promises` seperately: ```js import { readFileSync } from 'fs' import { readFile } from 'fs/promises' import { outputFile, outputFileSync } from 'fs-extra/esm' ``` Default exports are supported: ```js import fs from 'fs' import fse from 'fs-extra/esm' // fse.readFileSync is not a function; must use fs.readFileSync ``` but you probably want to just use regular `fs-extra` instead of `fs-extra/esm` for default exports: ```js import fs from 'fs-extra' // both fs and fs-extra methods are defined ``` Sync vs Async vs Async/Await ------------- Most methods are async by default. All async methods will return a promise if the callback isn't passed. Sync methods on the other hand will throw if an error occurs. Also Async/Await will throw an error if one occurs. Example: ```js const fs = require('fs-extra') // Async with promises: fs.copy('/tmp/myfile', '/tmp/mynewfile') .then(() => console.log('success!')) .catch(err => console.error(err)) // Async with callbacks: fs.copy('/tmp/myfile', '/tmp/mynewfile', err => { if (err) return console.error(err) console.log('success!') }) // Sync: try { fs.copySync('/tmp/myfile', '/tmp/mynewfile') console.log('success!') } catch (err) { console.error(err) } // Async/Await: async function copyFiles () { try { await fs.copy('/tmp/myfile', '/tmp/mynewfile') console.log('success!') } catch (err) { console.error(err) } } copyFiles() ``` Methods ------- ### Async - [copy](docs/copy.md) - [emptyDir](docs/emptyDir.md) - [ensureFile](docs/ensureFile.md) - [ensureDir](docs/ensureDir.md) - [ensureLink](docs/ensureLink.md) - [ensureSymlink](docs/ensureSymlink.md) - [mkdirp](docs/ensureDir.md) - [mkdirs](docs/ensureDir.md) - [move](docs/move.md) - [outputFile](docs/outputFile.md) - [outputJson](docs/outputJson.md) - [pathExists](docs/pathExists.md) - [readJson](docs/readJson.md) - [remove](docs/remove.md) - [writeJson](docs/writeJson.md) ### Sync - [copySync](docs/copy-sync.md) - [emptyDirSync](docs/emptyDir-sync.md) - [ensureFileSync](docs/ensureFile-sync.md) - [ensureDirSync](docs/ensureDir-sync.md) - [ensureLinkSync](docs/ensureLink-sync.md) - [ensureSymlinkSync](docs/ensureSymlink-sync.md) - [mkdirpSync](docs/ensureDir-sync.md) - [mkdirsSync](docs/ensureDir-sync.md) - [moveSync](docs/move-sync.md) - [outputFileSync](docs/outputFile-sync.md) - [outputJsonSync](docs/outputJson-sync.md) - [pathExistsSync](docs/pathExists-sync.md) - [readJsonSync](docs/readJson-sync.md) - [removeSync](docs/remove-sync.md) - [writeJsonSync](docs/writeJson-sync.md) **NOTE:** You can still use the native Node.js methods. They are promisified and copied over to `fs-extra`. See [notes on `fs.read()`, `fs.write()`, & `fs.writev()`](docs/fs-read-write-writev.md) ### What happened to `walk()` and `walkSync()`? They were removed from `fs-extra` in v2.0.0. If you need the functionality, `walk` and `walkSync` are available as separate packages, [`klaw`](https://github.com/jprichardson/node-klaw) and [`klaw-sync`](https://github.com/manidlou/node-klaw-sync). Third Party ----------- ### CLI [fse-cli](https://www.npmjs.com/package/@atao60/fse-cli) allows you to run `fs-extra` from a console or from [npm](https://www.npmjs.com) scripts. ### TypeScript If you like TypeScript, you can use `fs-extra` with it: https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/fs-extra ### File / Directory Watching If you want to watch for changes to files or directories, then you should use [chokidar](https://github.com/paulmillr/chokidar). ### Obtain Filesystem (Devices, Partitions) Information [fs-filesystem](https://github.com/arthurintelligence/node-fs-filesystem) allows you to read the state of the filesystem of the host on which it is run. It returns information about both the devices and the partitions (volumes) of the system. ### Misc. - [fs-extra-debug](https://github.com/jdxcode/fs-extra-debug) - Send your fs-extra calls to [debug](https://npmjs.org/package/debug). - [mfs](https://github.com/cadorn/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](http://nodei.co/npm/fs-extra.png?downloads=true&downloadRank=true&stars=true). This project uses [JavaScript Standard Style](https://github.com/feross/standard) - 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`. [![js-standard-style](https://cdn.rawgit.com/feross/standard/master/badge.svg)](https://github.com/feross/standard) 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. - Improve test coverage. Note: If you make any big changes, **you should definitely file an issue for discussion first.** ### Running the Test Suite fs-extra contains hundreds of tests. - `npm run lint`: runs the linter ([standard](http://standardjs.com/)) - `npm run unit`: runs the unit tests - `npm run unit-esm`: runs tests for `fs-extra/esm` exports - `npm test`: runs the linter and all tests When running unit tests, set the environment variable `CROSS_DEVICE_PATH` to the absolute path of an empty directory on another device (like a thumb drive) to enable cross-device move tests. ### Windows If you run the tests on the Windows and receive a lot of symbolic link `EPERM` permission errors, it's because on Windows you need elevated privilege to create symbolic links. You can add this to your Windows's account by following the instructions here: http://superuser.com/questions/104845/permission-to-make-symbolic-links-in-windows-7 However, I didn't have much luck doing this. Since I develop on Mac OS X, I use VMWare Fusion for Windows testing. I create a shared folder that I map to a drive on Windows. I open the `Node.js command prompt` and run as `Administrator`. I then map the network drive running the following command: net use z: "\\vmware-host\Shared Folders" I can then navigate to my `fs-extra` directory and run the tests. 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](http://nodejs.org/api/fs.html) 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: - [Isaac Shlueter](https://github.com/isaacs) - [Charlie McConnel](https://github.com/avianflu) - [James Halliday](https://github.com/substack) - [Andrew Kelley](https://github.com/andrewrk) License ------- Licensed under MIT Copyright (c) 2011-2024 [JP Richardson](https://github.com/jprichardson) [1]: http://nodejs.org/docs/latest/api/fs.html [jsonfile]: https://github.com/jprichardson/node-jsonfile ================================================ FILE: docs/copy-sync.md ================================================ # copySync(src, dest[, options]) Copy a file or directory. The directory can have contents. - `src` `` Note that if `src` is a directory it will copy everything inside of this directory, not the entire directory itself (see [issue #537](https://github.com/jprichardson/node-fs-extra/issues/537)). - `dest` `` Note that if `src` is a file, `dest` cannot be a directory (see [issue #323](https://github.com/jprichardson/node-fs-extra/issues/323)). - `options` `` - `overwrite` ``: overwrite existing file or directory, default is `true`. _Note that the copy operation will silently fail if you set this to `false` and the destination exists._ Use the `errorOnExist` option to change this behavior. - `errorOnExist` ``: when `overwrite` is `false` and the destination exists, throw an error. Default is `false`. - `dereference` ``: dereference symlinks, default is `false`. - `preserveTimestamps` ``: When true, will set last modification and access times to the ones of the original source files. When false, timestamp behavior is OS-dependent. Default is `false`. - `filter` ``: Function to filter copied files/directories. Return `true` to copy the item, `false` to ignore it. ## Example: ```js const fs = require('fs-extra') // copy file fs.copySync('/tmp/myfile', '/tmp/mynewfile') // copy directory, even if it has subdirectories or files fs.copySync('/tmp/mydir', '/tmp/mynewdir') ``` **Using filter function** ```js const fs = require('fs-extra') const filterFunc = (src, dest) => { // your logic here // it will be copied if return true } fs.copySync('/tmp/mydir', '/tmp/mynewdir', { filter: filterFunc }) ``` ================================================ FILE: docs/copy.md ================================================ # copy(src, dest[, options][, callback]) Copy a file or directory. The directory can have contents. - `src` `` Note that if `src` is a directory it will copy everything inside of this directory, not the entire directory itself (see [issue #537](https://github.com/jprichardson/node-fs-extra/issues/537)). - `dest` `` Note that if `src` is a file, `dest` cannot be a directory (see [issue #323](https://github.com/jprichardson/node-fs-extra/issues/323)). - `options` `` - `overwrite` ``: overwrite existing file or directory, default is `true`. _Note that the copy operation will silently fail if you set this to `false` and the destination exists._ Use the `errorOnExist` option to change this behavior. - `errorOnExist` ``: when `overwrite` is `false` and the destination exists, throw an error. Default is `false`. - `dereference` ``: dereference symlinks, default is `false`. - `preserveTimestamps` ``: When true, will set last modification and access times to the ones of the original source files. When false, timestamp behavior is OS-dependent. Default is `false`. - `filter` ``: Function to filter copied files/directories. Return `true` to copy the item, `false` to ignore it. Can also return a `Promise` that resolves to `true` or `false` (or pass in an `async` function). - `callback` `` - `err` `` ## Example: ```js const fs = require('fs-extra') // With a callback: fs.copy('/tmp/myfile', '/tmp/mynewfile', err => { if (err) return console.error(err) console.log('success!') }) // copies file fs.copy('/tmp/mydir', '/tmp/mynewdir', err => { if (err) return console.error(err) console.log('success!') }) // copies directory, even if it has subdirectories or files // With Promises: fs.copy('/tmp/myfile', '/tmp/mynewfile') .then(() => { console.log('success!') }) .catch(err => { console.error(err) }) // With async/await: async function example () { try { await fs.copy('/tmp/myfile', '/tmp/mynewfile') console.log('success!') } catch (err) { console.error(err) } } example() ``` **Using filter function** ```js const fs = require('fs-extra') const filterFunc = (src, dest) => { // your logic here // it will be copied if return true } fs.copy('/tmp/mydir', '/tmp/mynewdir', { filter: filterFunc }, err => { if (err) return console.error(err) console.log('success!') }) ``` ================================================ FILE: docs/emptyDir-sync.md ================================================ # emptyDirSync(dir) Ensures that a directory is empty. Deletes directory contents if the directory is not empty. If the directory does not exist, it is created. The directory itself is not deleted. **Alias:** `emptydirSync()` - `dir` `` ## Example: ```js const fs = require('fs-extra') // assume this directory has a lot of files and folders fs.emptyDirSync('/tmp/some/dir') ``` ================================================ FILE: docs/emptyDir.md ================================================ # emptyDir(dir[, callback]) Ensures that a directory is empty. Deletes directory contents if the directory is not empty. If the directory does not exist, it is created. The directory itself is not deleted. **Alias:** `emptydir()` - `dir` `` - `callback` `` - `err` `` ## Example: ```js const fs = require('fs-extra') // assume this directory has a lot of files and folders // With a callback: fs.emptyDir('/tmp/some/dir', err => { if (err) return console.error(err) console.log('success!') }) // With Promises: fs.emptyDir('/tmp/some/dir') .then(() => { console.log('success!') }) .catch(err => { console.error(err) }) // With async/await: async function example () { try { await fs.emptyDir('/tmp/some/dir') console.log('success!') } catch (err) { console.error(err) } } example() ``` ================================================ FILE: docs/ensureDir-sync.md ================================================ # ensureDirSync(dir[,options]) Ensures that the directory exists. If the directory structure does not exist, it is created. If provided, options may specify the desired mode for the directory. **Aliases:** `mkdirsSync()`, `mkdirpSync()` - `dir` `` - `options` ` | ` - If it is `Integer`, it will be `mode`. - If it is `Object`, it will be `{ mode: }`. ## Example: ```js const fs = require('fs-extra') const dir = '/tmp/this/path/does/not/exist' const desiredMode = 0o2775 const options = { mode: 0o2775 } fs.ensureDirSync(dir) // dir has now been created, including the directory it is to be placed in fs.ensureDirSync(dir, desiredMode) // dir has now been created, including the directory it is to be placed in with permission 0o2775 fs.ensureDirSync(dir, options) // dir has now been created, including the directory it is to be placed in with permission 0o2775 ``` ================================================ FILE: docs/ensureDir.md ================================================ # ensureDir(dir[,options][,callback]) Ensures that the directory exists. If the directory structure does not exist, it is created. **Aliases:** `mkdirs()`, `mkdirp()` - `dir` `` - `options` ` | ` - If it is `Integer`, it will be `mode`. - If it is `Object`, it will be `{ mode: }`. - `callback` `` - `err` `` ## Example: ```js const fs = require('fs-extra') const dir = '/tmp/this/path/does/not/exist' const desiredMode = 0o2775 const options = { mode: 0o2775 } // With a callback: fs.ensureDir(dir, err => { console.log(err) // => null // dir has now been created, including the directory it is to be placed in }) // With a callback and a mode integer fs.ensureDir(dir, desiredMode, err => { console.log(err) // => null // dir has now been created with mode 0o2775, including the directory it is to be placed in }) // With Promises: fs.ensureDir(dir) .then(() => { console.log('success!') }) .catch(err => { console.error(err) }) // With Promises and a mode integer: fs.ensureDir(dir, desiredMode) .then(() => { console.log('success!') }) .catch(err => { console.error(err) }) // With async/await: async function example (directory) { try { await fs.ensureDir(directory) console.log('success!') } catch (err) { console.error(err) } } example(dir) // With async/await and an options object, containing mode: async function exampleMode (directory) { try { await fs.ensureDir(directory, options) console.log('success!') } catch (err) { console.error(err) } } exampleMode(dir) ``` ================================================ FILE: docs/ensureFile-sync.md ================================================ # ensureFileSync(file) 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:** `createFileSync()` - `file` `` ## Example: ```js const fs = require('fs-extra') const file = '/tmp/this/path/does/not/exist/file.txt' fs.ensureFileSync(file) // file has now been created, including the directory it is to be placed in ``` ================================================ FILE: docs/ensureFile.md ================================================ # 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()` - `file` `` - `callback` `` - `err` `` ## Example: ```js const fs = require('fs-extra') const file = '/tmp/this/path/does/not/exist/file.txt' // With a callback: fs.ensureFile(file, err => { console.log(err) // => null // file has now been created, including the directory it is to be placed in }) // With Promises: fs.ensureFile(file) .then(() => { console.log('success!') }) .catch(err => { console.error(err) }) // With async/await: async function example (f) { try { await fs.ensureFile(f) console.log('success!') } catch (err) { console.error(err) } } example(file) ``` ================================================ FILE: docs/ensureLink-sync.md ================================================ # ensureLinkSync(srcPath, destPath) Ensures that the link exists. If the directory structure does not exist, it is created. **Alias:** `createLinkSync()` - `srcPath` `` - `destPath` `` ## Example: ```js const fs = require('fs-extra') const srcPath = '/tmp/file.txt' const destPath = '/tmp/this/path/does/not/exist/file.txt' fs.ensureLinkSync(srcPath, destPath) // link has now been created, including the directory it is to be placed in ``` ================================================ FILE: docs/ensureLink.md ================================================ # ensureLink(srcPath, destPath[, callback]) Ensures that the link exists. If the directory structure does not exist, it is created. **Alias:** `createLink()` - `srcPath` `` - `destPath` `` - `callback` `` - `err` `` ## Example: ```js const fs = require('fs-extra') const srcPath = '/tmp/file.txt' const destPath = '/tmp/this/path/does/not/exist/file.txt' // With a callback: fs.ensureLink(srcPath, destPath, err => { console.log(err) // => null // link has now been created, including the directory it is to be placed in }) // With Promises: fs.ensureLink(srcPath, destPath) .then(() => { console.log('success!') }) .catch(err => { console.error(err) }) // With async/await: async function example (src, dest) { try { await fs.ensureLink(src, dest) console.log('success!') } catch (err) { console.error(err) } } example(srcPath, destPath) ``` ================================================ FILE: docs/ensureSymlink-sync.md ================================================ # ensureSymlinkSync(srcPath, destPath[, type]) Ensures that the symlink exists. If the directory structure does not exist, it is created. **Alias:** `createSymlinkSync()` - `srcPath` `` - `destPath` `` - `type` `` It is only available on Windows and ignored on other platforms. It can be set to `dir`, `file`, or `junction`. ## Example: ```js const fs = require('fs-extra') const srcPath = '/tmp/file.txt' const destPath = '/tmp/this/path/does/not/exist/file.txt' fs.ensureSymlinkSync(srcPath, destPath) // symlink has now been created, including the directory it is to be placed in ``` ================================================ FILE: docs/ensureSymlink.md ================================================ # ensureSymlink(srcPath, destPath[, type][, callback]) Ensures that the symlink exists. If the directory structure does not exist, it is created. **Alias:** `createSymlink()` - `srcPath` `` - `destPath` `` - `type` `` It is only available on Windows and ignored on other platforms. It can be set to `dir`, `file`, or `junction`. - `callback` `` - `err` `` ## Example: ```js const fs = require('fs-extra') const srcPath = '/tmp/file.txt' const destPath = '/tmp/this/path/does/not/exist/file.txt' // With a callback: fs.ensureSymlink(srcPath, destPath, err => { console.log(err) // => null // symlink has now been created, including the directory it is to be placed in }) // With Promises: fs.ensureSymlink(srcPath, destPath) .then(() => { console.log('success!') }) .catch(err => { console.error(err) }) // With async/await: async function example (src, dest) { try { await fs.ensureSymlink(src, dest) console.log('success!') } catch (err) { console.error(err) } } example(srcPath, destPath) ``` ================================================ FILE: docs/fs-read-write-writev.md ================================================ # About `fs.read()` & `fs.write()` [`fs.read()`](https://nodejs.org/api/fs.html#fs_fs_read_fd_buffer_offset_length_position_callback), [`fs.write()`](https://nodejs.org/api/fs.html#fs_fs_write_fd_buffer_offset_length_position_callback), & [`fs.writev()`](https://nodejs.org/api/fs.html#fs_fs_writev_fd_buffers_position_callback) are different from other `fs` methods in that their callbacks are called with 3 arguments instead of the usual 2 arguments. If you're using them with callbacks, they will behave as usual. However, their promise usage is a little different. `fs-extra` promisifies these methods like [`util.promisify()`](https://nodejs.org/api/util.html#util_util_promisify_original) (only available in Node 8+) does. Here's the example promise usage: ## `fs.read()` ```js // With Promises: fs.read(fd, buffer, offset, length, position) .then(results => { console.log(results) // { bytesRead: 20, buffer: } }) // With async/await: async function example () { const { bytesRead, buffer } = await fs.read(fd, Buffer.alloc(length), offset, length, position) } ``` ## `fs.write()` ```js // With Promises: fs.write(fd, buffer, offset, length, position) .then(results => { console.log(results) // { bytesWritten: 20, buffer: } }) // With async/await: async function example () { const { bytesWritten, buffer } = await fs.write(fd, Buffer.alloc(length), offset, length, position) } ``` ## `fs.writev()` ```js // With async/await: async function example () { const { bytesWritten, buffers } = await fs.writev(fd, buffers, position) } ``` ================================================ FILE: docs/move-sync.md ================================================ # moveSync(src, dest[, options]) Moves a file or directory, even across devices. - `src` `` - `dest` `` Note: When `src` is a file, `dest` must be a file and when `src` is a directory, `dest` must be a directory. - `options` `` - `overwrite` ``: overwrite existing file or directory, default is `false`. ## Example: ```js const fs = require('fs-extra') fs.moveSync('/tmp/somefile', '/tmp/does/not/exist/yet/somefile') ``` **Using `overwrite` option** ```js const fs = require('fs-extra') fs.moveSync('/tmp/somedir', '/tmp/may/already/exist/somedir', { overwrite: true }) ``` ================================================ FILE: docs/move.md ================================================ # move(src, dest[, options][, callback]) Moves a file or directory, even across devices. - `src` `` - `dest` `` Note: When `src` is a file, `dest` must be a file and when `src` is a directory, `dest` must be a directory. - `options` `` - `overwrite` ``: overwrite existing file or directory, default is `false`. - `callback` `` - `err` `` ## Example: ```js const fs = require('fs-extra') const src = '/tmp/file.txt' const dest = '/tmp/this/path/does/not/exist/file.txt' // With a callback: fs.move(src, dest, err => { if (err) return console.error(err) console.log('success!') }) // With Promises: fs.move(src, dest) .then(() => { console.log('success!') }) .catch(err => { console.error(err) }) // With async/await: async function example (src, dest) { try { await fs.move(src, dest) console.log('success!') } catch (err) { console.error(err) } } example(src, dest) ``` **Using `overwrite` option** ```js const fs = require('fs-extra') fs.move('/tmp/somedir', '/tmp/may/already/exist/somedir', { overwrite: true }, err => { if (err) return console.error(err) console.log('success!') }) ``` ================================================ FILE: docs/outputFile-sync.md ================================================ # outputFileSync(file, data[, options]) Almost the same as `writeFileSync` (i.e. it overwrites), except that if the parent directory does not exist, it's created. `file` must be a file path (a buffer or a file descriptor is not allowed). - `file` `` - `data` ` | | ` - `options` ` | ` (the same as [`fs.writeFileSync()` options](https://nodejs.org/api/fs.html#fs_fs_writefilesync_file_data_options)) ## Example: ```js const fs = require('fs-extra') const file = '/tmp/this/path/does/not/exist/file.txt' fs.outputFileSync(file, 'hello!') const data = fs.readFileSync(file, 'utf8') console.log(data) // => hello! ``` ================================================ FILE: docs/outputFile.md ================================================ # outputFile(file, data[, options][, callback]) Almost the same as `writeFile` (i.e. it overwrites), except that if the parent directory does not exist, it's created. `file` must be a file path (a buffer or a file descriptor is not allowed). - `file` `` - `data` ` | | ` - `options` ` | ` (the same as [`fs.writeFile()` options](https://nodejs.org/api/fs.html#fs_fs_writefile_file_data_options_callback)) - `callback` `` - `err` `` ## Example: ```js const fs = require('fs-extra') const file = '/tmp/this/path/does/not/exist/file.txt' // With a callback: fs.outputFile(file, 'hello!', err => { console.log(err) // => null fs.readFile(file, 'utf8', (err, data) => { if (err) return console.error(err) console.log(data) // => hello! }) }) // With Promises: fs.outputFile(file, 'hello!') .then(() => fs.readFile(file, 'utf8')) .then(data => { console.log(data) // => hello! }) .catch(err => { console.error(err) }) // With async/await: async function example (f) { try { await fs.outputFile(f, 'hello!') const data = await fs.readFile(f, 'utf8') console.log(data) // => hello! } catch (err) { console.error(err) } } example(file) ``` ================================================ FILE: docs/outputJson-sync.md ================================================ # outputJsonSync(file, object[, options]) Almost the same as [`writeJsonSync`](writeJson-sync.md), except that if the directory does not exist, it's created. **Alias:** `outputJSONSync()` - `file` `` - `object` `` - `options` `` - `spaces` ` | ` Number of spaces to indent; or a string to use for indentation (i.e. pass `'\t'` for tab indentation). See [the docs](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#The_space_argument) for more info. - `EOL` `` Set EOL character. Default is `\n`. - `replacer` [JSON replacer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#The_replacer_parameter) - Also accepts [`fs.writeFileSync()` options](https://nodejs.org/api/fs.html#fs_fs_writefilesync_file_data_options) ## Example: ```js const fs = require('fs-extra') const file = '/tmp/this/path/does/not/exist/file.json' fs.outputJsonSync(file, {name: 'JP'}) const data = fs.readJsonSync(file) console.log(data.name) // => JP ``` ================================================ FILE: docs/outputJson.md ================================================ # outputJson(file, object[, options][, callback]) Almost the same as [`writeJson`](writeJson.md), except that if the directory does not exist, it's created. **Alias:** `outputJSON()` - `file` `` - `object` `` - `options` `` - `spaces` ` | ` Number of spaces to indent; or a string to use for indentation (i.e. pass `'\t'` for tab indentation). See [the docs](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#The_space_argument) for more info. - `EOL` `` Set EOL character. Default is `\n`. - `replacer` [JSON replacer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#The_replacer_parameter) - Also accepts [`fs.writeFile()` options](https://nodejs.org/api/fs.html#fs_fs_writefile_file_data_options_callback) - `callback` `` - `err` `` ## Example: ```js const fs = require('fs-extra') const file = '/tmp/this/path/does/not/exist/file.json' // With a callback: fs.outputJson(file, {name: 'JP'}, err => { console.log(err) // => null fs.readJson(file, (err, data) => { if (err) return console.error(err) console.log(data.name) // => JP }) }) // With Promises: fs.outputJson(file, {name: 'JP'}) .then(() => fs.readJson(file)) .then(data => { console.log(data.name) // => JP }) .catch(err => { console.error(err) }) // With async/await: async function example (f) { try { await fs.outputJson(f, {name: 'JP'}) const data = await fs.readJson(f) console.log(data.name) // => JP } catch (err) { console.error(err) } } example(file) ``` ================================================ FILE: docs/pathExists-sync.md ================================================ # pathExistsSync(file) An alias for [`fs.existsSync()`](https://nodejs.org/api/fs.html#fs_fs_existssync_path), created for consistency with [`pathExists()`](pathExists.md). ================================================ FILE: docs/pathExists.md ================================================ # pathExists(file[, callback]) Test whether or not the given path exists by checking with the file system. Like [`fs.exists`](https://nodejs.org/api/fs.html#fs_fs_exists_path_callback), but with a normal callback signature (err, exists). Uses `fs.access` under the hood. - `file` `` - `callback` `` - `err` `` - `exists` `` ## Example: ```js const fs = require('fs-extra') const file = '/tmp/this/path/does/not/exist/file.txt' // With a callback: fs.pathExists(file, (err, exists) => { console.log(err) // => null console.log(exists) // => false }) // Promise usage: fs.pathExists(file) .then(exists => console.log(exists)) // => false // With async/await: async function example (f) { const exists = await fs.pathExists(f) console.log(exists) // => false } example(file) ``` ================================================ FILE: docs/readJson-sync.md ================================================ # readJsonSync(file[, options]) Reads a JSON file and then parses it into an object. **Alias:** `readJSONSync()` - `file` `` - `options` `` (the same as [`jsonFile.readFileSync()` options](https://github.com/jprichardson/node-jsonfile#readfilesyncfilename-options)) ## Example: ```js const fs = require('fs-extra') const packageObj = fs.readJsonSync('./package.json') console.log(packageObj.version) // => 2.0.0 ``` --- `readJsonSync()` can take a `throws` option set to `false` and it won't throw if the JSON is invalid. Example: ```js const fs = require('fs-extra') const file = '/tmp/some-invalid.json' const data = '{not valid JSON' fs.writeFileSync(file, data) const obj = fs.readJsonSync(file, { throws: false }) console.log(obj) // => null ``` ================================================ FILE: docs/readJson.md ================================================ # readJson(file[, options][, callback]) Reads a JSON file and then parses it into an object. **Alias:** `readJSON()` - `file` `` - `options` `` (the same as [`jsonFile.readFile()` options](https://github.com/jprichardson/node-jsonfile#readfilefilename-options-callback)) - `callback` `` - `err` `` - `obj` `` ## Example: ```js const fs = require('fs-extra') // With a callback: fs.readJson('./package.json', (err, packageObj) => { if (err) console.error(err) console.log(packageObj.version) // => 0.1.3 }) // With Promises: fs.readJson('./package.json') .then(packageObj => { console.log(packageObj.version) // => 0.1.3 }) .catch(err => { console.error(err) }) // With async/await: async function example () { try { const packageObj = await fs.readJson('./package.json') console.log(packageObj.version) // => 0.1.3 } catch (err) { console.error(err) } } example() ``` --- `readJson()` can take a `throws` option set to `false` and it won't throw if the JSON is invalid. Example: ```js const fs = require('fs-extra') const file = '/tmp/some-invalid.json' const data = '{not valid JSON' fs.writeFileSync(file, data) // With a callback: fs.readJson(file, { throws: false }, (err, obj) => { if (err) console.error(err) console.log(obj) // => null }) // With Promises: fs.readJson(file, { throws: false }) .then(obj => { console.log(obj) // => null }) .catch(err => { console.error(err) // Not called }) // With async/await: async function example (f) { const obj = await fs.readJson(f, { throws: false }) console.log(obj) // => null } example(file) ``` ================================================ FILE: docs/remove-sync.md ================================================ # removeSync(path) Removes a file or directory. The directory can have contents. If the path does not exist, silently does nothing. - `path` `` ## Example: ```js const fs = require('fs-extra') // remove file fs.removeSync('/tmp/myfile') fs.removeSync('/home/jprichardson') // I just deleted my entire HOME directory. ``` ================================================ FILE: docs/remove.md ================================================ # remove(path[, callback]) Removes a file or directory. The directory can have contents. If the path does not exist, silently does nothing. - `path` `` - `callback` `` - `err` `` ## Example: ```js const fs = require('fs-extra') // remove file // With a callback: fs.remove('/tmp/myfile', err => { if (err) return console.error(err) console.log('success!') }) fs.remove('/home/jprichardson', err => { if (err) return console.error(err) console.log('success!') // I just deleted my entire HOME directory. }) // With Promises: fs.remove('/tmp/myfile') .then(() => { console.log('success!') }) .catch(err => { console.error(err) }) // With async/await: async function example (src, dest) { try { await fs.remove('/tmp/myfile') console.log('success!') } catch (err) { console.error(err) } } example() ``` ================================================ FILE: docs/writeJson-sync.md ================================================ # writeJsonSync(file, object[, options]) Writes an object to a JSON file. **Alias:** `writeJSONSync()` - `file` `` - `object` `` - `options` `` - `spaces` ` | ` Number of spaces to indent; or a string to use for indentation (i.e. pass `'\t'` for tab indentation). See [the docs](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#The_space_argument) for more info. - `EOL` `` Set EOL character. Default is `\n`. - `replacer` [JSON replacer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#The_replacer_parameter) - Also accepts [`fs.writeFileSync()` options](https://nodejs.org/api/fs.html#fs_fs_writefilesync_file_data_options) ## Example: ```js const fs = require('fs-extra') fs.writeJsonSync('./package.json', {name: 'fs-extra'}) ``` --- **See also:** [`outputJsonSync()`](outputJson-sync.md) ================================================ FILE: docs/writeJson.md ================================================ # writeJson(file, object[, options][, callback]) Writes an object to a JSON file. **Alias:** `writeJSON()` - `file` `` - `object` `` - `options` `` - `spaces` ` | ` Number of spaces to indent; or a string to use for indentation (i.e. pass `'\t'` for tab indentation). See [the docs](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#The_space_argument) for more info. - `EOL` `` Set EOL character. Default is `\n`. - `replacer` [JSON replacer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#The_replacer_parameter) - Also accepts [`fs.writeFile()` options](https://nodejs.org/api/fs.html#fs_fs_writefile_file_data_options_callback) - `callback` `` - `err` `` ## Example: ```js const fs = require('fs-extra') // With a callback: fs.writeJson('./package.json', {name: 'fs-extra'}, err => { if (err) return console.error(err) console.log('success!') }) // With Promises: fs.writeJson('./package.json', {name: 'fs-extra'}) .then(() => { console.log('success!') }) .catch(err => { console.error(err) }) // With async/await: async function example () { try { await fs.writeJson('./package.json', {name: 'fs-extra'}) console.log('success!') } catch (err) { console.error(err) } } example() ``` --- **See also:** [`outputJson()`](outputJson.md) ================================================ FILE: lib/__tests__/promise.test.js ================================================ 'use strict' /* eslint-env mocha */ const assert = require('assert') const fse = require('..') const methods = [ 'emptyDir', 'ensureFile', 'ensureDir', 'mkdirs', 'readJson', 'readJSON', 'remove' ] describe('promise support', () => { methods.forEach(method => { it(method, done => { fse[method]().catch(() => done()) }) }) it('provides fse.promises API', () => { assert.ok(fse.promises) assert.strictEqual(typeof fse.promises.writeFile, 'function') }) }) ================================================ FILE: lib/copy/__tests__/copy-broken-symlink.test.js ================================================ 'use strict' const fs = require('fs') const os = require('os') const fse = require('../..') const path = require('path') const assert = require('assert') const { copy } = require('../') /* global afterEach, beforeEach, describe, it */ describe('copy / broken symlink', () => { const TEST_DIR = path.join(os.tmpdir(), 'fs-extra', 'copy-broken-symlink') const src = path.join(TEST_DIR, 'src') const dest = path.join(TEST_DIR, 'dest') beforeEach(done => { fse.emptyDir(TEST_DIR, err => { assert.ifError(err) createFixtures(src, done) }) }) afterEach(done => fse.remove(TEST_DIR, done)) describe('when symlink is broken', () => { it('should not throw error if dereference is false', done => { copy(src, dest, err => { assert.strictEqual(err, null) done() }) }) it('should throw error if dereference is true', done => { copy(src, dest, { dereference: true }, err => { assert.strictEqual(err.code, 'ENOENT') done() }) }) }) }) function createFixtures (srcDir, callback) { fs.mkdir(srcDir, err => { let brokenFile let brokenFileLink if (err) return callback(err) try { brokenFile = path.join(srcDir, 'does-not-exist') brokenFileLink = path.join(srcDir, 'broken-symlink') fs.writeFileSync(brokenFile, 'does not matter') fs.symlinkSync(brokenFile, brokenFileLink, 'file') } catch (err) { callback(err) } // break the symlink now fse.remove(brokenFile, callback) }) } ================================================ FILE: lib/copy/__tests__/copy-case-insensitive-paths.test.js ================================================ 'use strict' const assert = require('assert') const os = require('os') const path = require('path') const fs = require('../../') const platform = os.platform() /* global beforeEach, afterEach, describe, it */ describe('+ copy() - case insensitive paths', () => { let TEST_DIR = '' let src = '' let dest = '' beforeEach(done => { TEST_DIR = path.join(os.tmpdir(), 'fs-extra', 'copy-case-insensitive-paths') fs.emptyDir(TEST_DIR, done) }) afterEach(done => fs.remove(TEST_DIR, done)) describe('> when src is a directory', () => { it('should behave correctly based on the OS', done => { src = path.join(TEST_DIR, 'srcdir') fs.outputFileSync(path.join(src, 'subdir', 'file.txt'), 'some data') dest = path.join(TEST_DIR, 'srcDir') fs.copy(src, dest, err => { if (platform === 'linux') { assert.ifError(err) assert(fs.existsSync(dest)) assert.strictEqual(fs.readFileSync(path.join(dest, 'subdir', 'file.txt'), 'utf8'), 'some data') } if (platform === 'darwin' || platform === 'win32') { assert.strictEqual(err.message, 'Source and destination must not be the same.') } done() }) }) }) describe('> when src is a file', () => { it('should behave correctly based on the OS', done => { src = path.join(TEST_DIR, 'srcfile') fs.outputFileSync(src, 'some data') dest = path.join(TEST_DIR, 'srcFile') fs.copy(src, dest, err => { if (platform === 'linux') { assert.ifError(err) assert(fs.existsSync(dest)) assert.strictEqual(fs.readFileSync(dest, 'utf8'), 'some data') } if (platform === 'darwin' || platform === 'win32') { assert.strictEqual(err.message, 'Source and destination must not be the same.') } done() }) }) }) describe('> when src is a symlink', () => { it('should behave correctly based on the OS, symlink dir', done => { src = path.join(TEST_DIR, 'srcdir') fs.outputFileSync(path.join(src, 'subdir', 'file.txt'), 'some data') const srcLink = path.join(TEST_DIR, 'src-symlink') fs.symlinkSync(src, srcLink, 'dir') dest = path.join(TEST_DIR, 'src-Symlink') fs.copy(srcLink, dest, err => { if (platform === 'linux') { assert.ifError(err) assert(fs.existsSync(dest)) assert.strictEqual(fs.readFileSync(path.join(dest, 'subdir', 'file.txt'), 'utf8'), 'some data') const destLink = fs.readlinkSync(dest) assert.strictEqual(destLink, src) } if (platform === 'darwin' || platform === 'win32') { assert.strictEqual(err.message, 'Source and destination must not be the same.') } done() }) }) it('should behave correctly based on the OS, symlink file', done => { src = path.join(TEST_DIR, 'srcfile') fs.outputFileSync(src, 'some data') const srcLink = path.join(TEST_DIR, 'src-symlink') fs.symlinkSync(src, srcLink, 'file') dest = path.join(TEST_DIR, 'src-Symlink') fs.copy(srcLink, dest, err => { if (platform === 'linux') { assert.ifError(err) assert(fs.existsSync(dest)) assert.strictEqual(fs.readFileSync(dest, 'utf8'), 'some data') const destLink = fs.readlinkSync(dest) assert.strictEqual(destLink, src) } if (platform === 'darwin' || platform === 'win32') { assert.strictEqual(err.message, 'Source and destination must not be the same.') } done() }) }) }) }) ================================================ FILE: lib/copy/__tests__/copy-dev-null.test.js ================================================ 'use strict' const fs = require('fs') const os = require('os') const fse = require('../../') const path = require('path') const assert = require('assert') /* global afterEach, beforeEach, describe, it */ let TEST_DIR = '' describe('+ copy() - copy /dev/null', () => { beforeEach(done => { TEST_DIR = path.join(os.tmpdir(), 'test', 'fs-extra', 'copy-dev-null') fse.emptyDir(TEST_DIR, done) }) afterEach(done => fse.remove(TEST_DIR, done)) describe('> when src is /dev/null', () => { it('should copy successfully', done => { // no /dev/null on windows if (process.platform === 'win32') return done() const tmpFile = path.join(TEST_DIR, 'foo') fse.copy('/dev/null', tmpFile, err => { assert.ifError(err) const stats = fs.lstatSync(tmpFile) assert.strictEqual(stats.size, 0) done() }) }) }) }) ================================================ FILE: lib/copy/__tests__/copy-gh-89.test.js ================================================ 'use strict' // relevant: https://github.com/jprichardson/node-fs-extra/issues/89 // come up with better file name const fs = require('fs') const os = require('os') const fse = require('../../') const path = require('path') const assert = require('assert') /* global afterEach, beforeEach, describe, it */ describe('copy() - gh #89', () => { const TEST_DIR = path.join(os.tmpdir(), 'fs-extra', 'copy-gh-89') beforeEach(done => { fse.emptyDir(TEST_DIR, done) }) afterEach(done => { fse.remove(TEST_DIR, done) }) it('should copy successfully', done => { const A = path.join(TEST_DIR, 'A') const B = path.join(TEST_DIR, 'B') fs.mkdirSync(A) fs.mkdirSync(B) const one = path.join(A, 'one.txt') const two = path.join(A, 'two.txt') const three = path.join(B, 'three.txt') const four = path.join(B, 'four.txt') fs.writeFileSync(one, '1') fs.writeFileSync(two, '2') fs.writeFileSync(three, '3') fs.writeFileSync(four, '4') const C = path.join(TEST_DIR, 'C') fse.copy(A, C, err => { if (err) return done(err) fse.copy(B, C, err => { if (err) return done(err) assert(fs.existsSync(path.join(C, 'one.txt'))) assert(fs.existsSync(path.join(C, 'two.txt'))) assert(fs.existsSync(path.join(C, 'three.txt'))) assert(fs.existsSync(path.join(C, 'four.txt'))) done() }) }) }) }) ================================================ FILE: lib/copy/__tests__/copy-permissions.test.js ================================================ 'use strict' const fs = require('fs') const os = require('os') const fse = require('../../') const path = require('path') const assert = require('assert') /* global beforeEach, describe, it */ describe('copy', () => { let TEST_DIR beforeEach(done => { TEST_DIR = path.join(os.tmpdir(), 'fs-extra', 'copy') fse.emptyDir(TEST_DIR, done) }) // pretty UNIX specific, may not pass on windows... only tested on Mac OS X 10.9 it('should maintain file permissions and ownership', done => { if (process.platform === 'win32') return done() // var userid = require('userid') // http://man7.org/linux/man-pages/man2/stat.2.html const S_IFREG = 0o100000 // regular file const S_IFDIR = 0o40000 // directory // these are Mac specific I think (at least staff), should find Linux equivalent let gidWheel let gidStaff try { gidWheel = process.getgid() // userid.gid('wheel') } catch { gidWheel = process.getgid() } try { gidStaff = process.getgid() // userid.gid('staff') } catch { gidStaff = process.getgid() } const permDir = path.join(TEST_DIR, 'perms') fs.mkdirSync(permDir) const srcDir = path.join(permDir, 'src') fs.mkdirSync(srcDir) const f1 = path.join(srcDir, 'f1.txt') fs.writeFileSync(f1, '') fs.chmodSync(f1, 0o666) fs.chownSync(f1, process.getuid(), gidWheel) const f1stats = fs.lstatSync(f1) assert.strictEqual(f1stats.mode - S_IFREG, 0o666) const d1 = path.join(srcDir, 'somedir') fs.mkdirSync(d1) fs.chmodSync(d1, 0o777) fs.chownSync(d1, process.getuid(), gidStaff) const d1stats = fs.lstatSync(d1) assert.strictEqual(d1stats.mode - S_IFDIR, 0o777) const f2 = path.join(d1, 'f2.bin') fs.writeFileSync(f2, '') fs.chmodSync(f2, 0o777) fs.chownSync(f2, process.getuid(), gidStaff) const f2stats = fs.lstatSync(f2) assert.strictEqual(f2stats.mode - S_IFREG, 0o777) const d2 = path.join(srcDir, 'crazydir') fs.mkdirSync(d2) fs.chmodSync(d2, 0o444) fs.chownSync(d2, process.getuid(), gidWheel) const d2stats = fs.lstatSync(d2) assert.strictEqual(d2stats.mode - S_IFDIR, 0o444) const destDir = path.join(permDir, 'dest') fse.copy(srcDir, destDir, err => { assert.ifError(err) const newf1stats = fs.lstatSync(path.join(permDir, 'dest/f1.txt')) const newd1stats = fs.lstatSync(path.join(permDir, 'dest/somedir')) const newf2stats = fs.lstatSync(path.join(permDir, 'dest/somedir/f2.bin')) const newd2stats = fs.lstatSync(path.join(permDir, 'dest/crazydir')) assert.strictEqual(newf1stats.mode, f1stats.mode) assert.strictEqual(newd1stats.mode, d1stats.mode) assert.strictEqual(newf2stats.mode, f2stats.mode) assert.strictEqual(newd2stats.mode, d2stats.mode) assert.strictEqual(newf1stats.gid, f1stats.gid) assert.strictEqual(newd1stats.gid, d1stats.gid) assert.strictEqual(newf2stats.gid, f2stats.gid) assert.strictEqual(newd2stats.gid, d2stats.gid) assert.strictEqual(newf1stats.uid, f1stats.uid) assert.strictEqual(newd1stats.uid, d1stats.uid) assert.strictEqual(newf2stats.uid, f2stats.uid) assert.strictEqual(newd2stats.uid, d2stats.uid) done() }) }) }) ================================================ FILE: lib/copy/__tests__/copy-preserve-timestamp.test.js ================================================ 'use strict' const fs = require('../../') const os = require('os') const path = require('path') const { copy } = require('../') const utimesSync = require('../../util/utimes').utimesMillisSync const assert = require('assert') /* global beforeEach, afterEach, describe, it */ if (process.arch === 'ia32') console.warn('32 bit arch; skipping copy timestamp tests') const describeIfPractical = process.arch === 'ia32' ? describe.skip : describe describeIfPractical('copy() - preserve timestamp', () => { let TEST_DIR, SRC, DEST, FILES function setupFixture (readonly) { TEST_DIR = path.join(os.tmpdir(), 'fs-extra', 'copy-preserve-timestamp') SRC = path.join(TEST_DIR, 'src') DEST = path.join(TEST_DIR, 'dest') FILES = ['a-file', path.join('a-folder', 'another-file'), path.join('a-folder', 'another-folder', 'file3')] const timestamp = Date.now() / 1000 - 5 FILES.forEach(f => { const filePath = path.join(SRC, f) fs.ensureFileSync(filePath) // rewind timestamps to make sure that coarser OS timestamp resolution // does not alter results utimesSync(filePath, timestamp, timestamp) if (readonly) { fs.chmodSync(filePath, 0o444) } }) } afterEach(done => fs.remove(TEST_DIR, done)) describe('> when preserveTimestamps option is true', () => { ;[ { subcase: 'writable', readonly: false }, { subcase: 'readonly', readonly: true } ].forEach(params => { describe(`>> with ${params.subcase} source files`, () => { beforeEach(() => setupFixture(params.readonly)) it('should have the same timestamps on copy', done => { copy(SRC, DEST, { preserveTimestamps: true }, (err) => { if (err) return done(err) FILES.forEach(testFile({ preserveTimestamps: true })) done() }) }) }) }) }) function testFile (options) { return function (file) { const a = path.join(SRC, file) const b = path.join(DEST, file) const fromStat = fs.statSync(a) const toStat = fs.statSync(b) if (options.preserveTimestamps) { // Windows sub-second precision fixed: https://github.com/nodejs/io.js/issues/2069 assert.strictEqual(toStat.mtime.getTime(), fromStat.mtime.getTime(), 'different mtime values') assert.strictEqual(toStat.atime.getTime(), fromStat.atime.getTime(), 'different atime values') } else { // the access time might actually be the same, so check only modification time assert.notStrictEqual(toStat.mtime.getTime(), fromStat.mtime.getTime(), 'same mtime values') } } } }) ================================================ FILE: lib/copy/__tests__/copy-prevent-copying-identical.test.js ================================================ 'use strict' const assert = require('assert') const os = require('os') const path = require('path') const fs = require('../../') const klawSync = require('klaw-sync') /* global beforeEach, afterEach, describe, it */ describe('+ copy() - prevent copying identical files and dirs', () => { let TEST_DIR = '' let src = '' let dest = '' beforeEach(done => { TEST_DIR = path.join(os.tmpdir(), 'fs-extra', 'copy-prevent-copying-identical') fs.emptyDir(TEST_DIR, done) }) afterEach(done => fs.remove(TEST_DIR, done)) it('should return an error if src and dest are the same', done => { const fileSrc = path.join(TEST_DIR, 'TEST_fs-extra_copy') const fileDest = path.join(TEST_DIR, 'TEST_fs-extra_copy') fs.ensureFileSync(fileSrc) fs.copy(fileSrc, fileDest, err => { assert.strictEqual(err.message, 'Source and destination must not be the same.') done() }) }) describe('dest with parent symlink', () => { describe('first parent is symlink', () => { it('should error when src is file', done => { const src = path.join(TEST_DIR, 'a', 'file.txt') const dest = path.join(TEST_DIR, 'b', 'file.txt') const srcParent = path.join(TEST_DIR, 'a') const destParent = path.join(TEST_DIR, 'b') fs.ensureFileSync(src) fs.ensureSymlinkSync(srcParent, destParent, 'dir') fs.copy(src, dest, err => { assert.strictEqual(err.message, 'Source and destination must not be the same.') assert(fs.existsSync(src)) done() }) }) it('should error when src is directory', done => { const src = path.join(TEST_DIR, 'a', 'foo') const dest = path.join(TEST_DIR, 'b', 'foo') const srcParent = path.join(TEST_DIR, 'a') const destParent = path.join(TEST_DIR, 'b') fs.ensureDirSync(src) fs.ensureSymlinkSync(srcParent, destParent, 'dir') fs.copy(src, dest, err => { assert.strictEqual(err.message, 'Source and destination must not be the same.') assert(fs.existsSync(src)) done() }) }) }) describe('nested dest', () => { it('should error when src is file', done => { const src = path.join(TEST_DIR, 'a', 'dir', 'file.txt') const dest = path.join(TEST_DIR, 'b', 'dir', 'file.txt') const srcParent = path.join(TEST_DIR, 'a') const destParent = path.join(TEST_DIR, 'b') fs.ensureFileSync(src) fs.ensureSymlinkSync(srcParent, destParent, 'dir') fs.copy(src, dest, err => { assert.strictEqual(err.message, 'Source and destination must not be the same.') assert(fs.existsSync(src)) done() }) }) it('should error when src is directory', done => { const src = path.join(TEST_DIR, 'a', 'dir', 'foo') const dest = path.join(TEST_DIR, 'b', 'dir', 'foo') const srcParent = path.join(TEST_DIR, 'a') const destParent = path.join(TEST_DIR, 'b') fs.ensureDirSync(src) fs.ensureSymlinkSync(srcParent, destParent, 'dir') fs.copy(src, dest, err => { assert.strictEqual(err.message, 'Source and destination must not be the same.') assert(fs.existsSync(src)) done() }) }) }) }) // src is directory: // src is regular, dest is symlink // src is symlink, dest is regular // src is symlink, dest is symlink describe('> when src is a directory', () => { describe('>> when src is regular and dest is a symlink that points to src', () => { it('should error if dereference is true', done => { src = path.join(TEST_DIR, 'src') fs.mkdirsSync(src) const subdir = path.join(TEST_DIR, 'src', 'subdir') fs.mkdirsSync(subdir) fs.writeFileSync(path.join(subdir, 'file.txt'), 'some data') const destLink = path.join(TEST_DIR, 'dest-symlink') fs.symlinkSync(src, destLink, 'dir') const oldlen = klawSync(src).length fs.copy(src, destLink, { dereference: true }, err => { assert.strictEqual(err.message, 'Source and destination must not be the same.') const newlen = klawSync(src).length assert.strictEqual(newlen, oldlen) const link = fs.readlinkSync(destLink) assert.strictEqual(link, src) done() }) }) }) describe('>> when src is a symlink that points to a regular dest', () => { it('should throw error', done => { dest = path.join(TEST_DIR, 'dest') fs.mkdirsSync(dest) const subdir = path.join(TEST_DIR, 'dest', 'subdir') fs.mkdirsSync(subdir) fs.writeFileSync(path.join(subdir, 'file.txt'), 'some data') const srcLink = path.join(TEST_DIR, 'src-symlink') fs.symlinkSync(dest, srcLink, 'dir') const oldlen = klawSync(dest).length fs.copy(srcLink, dest, err => { assert.ok(err) // assert nothing copied const newlen = klawSync(dest).length assert.strictEqual(newlen, oldlen) const link = fs.readlinkSync(srcLink) assert.strictEqual(link, dest) done() }) }) }) describe('>> when src and dest are symlinks that point to the exact same path', () => { it('should error src and dest are the same and dereference is true', done => { src = path.join(TEST_DIR, 'src') fs.mkdirsSync(src) const srcLink = path.join(TEST_DIR, 'src_symlink') fs.symlinkSync(src, srcLink, 'dir') const destLink = path.join(TEST_DIR, 'dest_symlink') fs.symlinkSync(src, destLink, 'dir') const srclenBefore = klawSync(srcLink).length const destlenBefore = klawSync(destLink).length fs.copy(srcLink, destLink, { dereference: true }, err => { assert.strictEqual(err.message, 'Source and destination must not be the same.') const srclenAfter = klawSync(srcLink).length assert.strictEqual(srclenAfter, srclenBefore, 'src length should not change') const destlenAfter = klawSync(destLink).length assert.strictEqual(destlenAfter, destlenBefore, 'dest length should not change') const srcln = fs.readlinkSync(srcLink) assert.strictEqual(srcln, src) const destln = fs.readlinkSync(destLink) assert.strictEqual(destln, src) done() }) }) }) }) // src is file: // src is regular, dest is symlink // src is symlink, dest is regular // src is symlink, dest is symlink describe('> when src is a file', () => { describe('>> when src is regular and dest is a symlink that points to src', () => { it('should error', done => { src = path.join(TEST_DIR, 'src.txt') fs.outputFileSync(src, 'some data') const destLink = path.join(TEST_DIR, 'dest-symlink') fs.symlinkSync(src, destLink, 'file') fs.copy(src, destLink, { dereference: true }, err => { assert.strictEqual(err.message, 'Source and destination must not be the same.') done() }) }) }) describe('>> when src is a symlink that points to a regular dest', () => { it('should throw error if dereference is true', done => { dest = path.join(TEST_DIR, 'dest', 'somefile.txt') fs.outputFileSync(dest, 'some data') const srcLink = path.join(TEST_DIR, 'src-symlink') fs.symlinkSync(dest, srcLink, 'file') fs.copy(srcLink, dest, { dereference: true }, err => { assert.strictEqual(err.message, 'Source and destination must not be the same.') const link = fs.readlinkSync(srcLink) assert.strictEqual(link, dest) assert(fs.readFileSync(link, 'utf8'), 'some data') done() }) }) }) describe('>> when src and dest are symlinks that point to the exact same path', () => { it('should error src and dest are the same and dereferene is true', done => { src = path.join(TEST_DIR, 'src', 'srcfile.txt') fs.outputFileSync(src, 'src data') const srcLink = path.join(TEST_DIR, 'src_symlink') fs.symlinkSync(src, srcLink, 'file') const destLink = path.join(TEST_DIR, 'dest_symlink') fs.symlinkSync(src, destLink, 'file') fs.copy(srcLink, destLink, { dereference: true }, err => { assert.strictEqual(err.message, 'Source and destination must not be the same.') const srcln = fs.readlinkSync(srcLink) assert.strictEqual(srcln, src) const destln = fs.readlinkSync(destLink) assert.strictEqual(destln, src) assert(fs.readFileSync(srcln, 'utf8'), 'src data') assert(fs.readFileSync(destln, 'utf8'), 'src data') done() }) }) }) }) }) ================================================ FILE: lib/copy/__tests__/copy-prevent-copying-into-itself.test.js ================================================ 'use strict' const assert = require('assert') const os = require('os') const path = require('path') const fs = require('../../') const klawSync = require('klaw-sync') /* global beforeEach, afterEach, describe, it */ // these files are used for all tests const FILES = [ 'file0.txt', path.join('dir1', 'file1.txt'), path.join('dir1', 'dir2', 'file2.txt'), path.join('dir1', 'dir2', 'dir3', 'file3.txt') ] const dat0 = 'file0' const dat1 = 'file1' const dat2 = 'file2' const dat3 = 'file3' describe('+ copy() - prevent copying into itself', () => { let TEST_DIR, src beforeEach(done => { TEST_DIR = path.join(os.tmpdir(), 'fs-extra', 'copy-prevent-copying-into-itself') src = path.join(TEST_DIR, 'src') fs.mkdirpSync(src) fs.outputFileSync(path.join(src, FILES[0]), dat0) fs.outputFileSync(path.join(src, FILES[1]), dat1) fs.outputFileSync(path.join(src, FILES[2]), dat2) fs.outputFileSync(path.join(src, FILES[3]), dat3) done() }) afterEach(done => fs.remove(TEST_DIR, done)) describe('> when source is a file', () => { it('should copy the file successfully even if dest parent is a subdir of src', done => { const srcFile = path.join(TEST_DIR, 'src', 'srcfile.txt') const destFile = path.join(TEST_DIR, 'src', 'dest', 'destfile.txt') fs.writeFileSync(srcFile, dat0) fs.copy(srcFile, destFile, err => { assert.ifError(err) assert(fs.existsSync(destFile, 'file copied')) const out = fs.readFileSync(destFile, 'utf8') assert.strictEqual(out, dat0, 'file contents matched') done() }) }) }) // test for these cases: // - src is directory, dest is directory // - src is directory, dest is symlink // - src is symlink, dest is directory // - src is symlink, dest is symlink describe('> when source is a directory', () => { describe('>> when dest is a directory', () => { it('of not itself', done => { const dest = path.join(TEST_DIR, src.replace(/^\w:/, '')) return testSuccess(src, dest, done) }) it('of itself', done => { const dest = path.join(src, 'dest') return testError(src, dest, done) }) it("should copy the directory successfully when dest is 'src_dest'", done => { const dest = path.join(TEST_DIR, 'src_dest') return testSuccess(src, dest, done) }) it("should copy the directory successfully when dest is 'src-dest'", done => { const dest = path.join(TEST_DIR, 'src-dest') return testSuccess(src, dest, done) }) it("should copy the directory successfully when dest is 'dest_src'", done => { const dest = path.join(TEST_DIR, 'dest_src') return testSuccess(src, dest, done) }) it("should copy the directory successfully when dest is 'src_dest/src'", done => { const dest = path.join(TEST_DIR, 'src_dest', 'src') return testSuccess(src, dest, done) }) it("should copy the directory successfully when dest is 'src-dest/src'", done => { const dest = path.join(TEST_DIR, 'src-dest', 'src') return testSuccess(src, dest, done) }) it("should copy the directory successfully when dest is 'dest_src/src'", done => { const dest = path.join(TEST_DIR, 'dest_src', 'src') return testSuccess(src, dest, done) }) it("should copy the directory successfully when dest is 'src_src/dest'", done => { const dest = path.join(TEST_DIR, 'src_src', 'dest') return testSuccess(src, dest, done) }) it("should copy the directory successfully when dest is 'src-src/dest'", done => { const dest = path.join(TEST_DIR, 'src-src', 'dest') return testSuccess(src, dest, done) }) it("should copy the directory successfully when dest is 'srcsrc/dest'", done => { const dest = path.join(TEST_DIR, 'srcsrc', 'dest') return testSuccess(src, dest, done) }) it("should copy the directory successfully when dest is 'dest/src'", done => { const dest = path.join(TEST_DIR, 'dest', 'src') return testSuccess(src, dest, done) }) it('should copy the directory successfully when dest is very nested that all its parents need to be created', done => { const dest = path.join(TEST_DIR, 'dest', 'src', 'foo', 'bar', 'baz', 'qux', 'quux', 'waldo', 'grault', 'garply', 'fred', 'plugh', 'thud', 'some', 'highly', 'deeply', 'badly', 'nasty', 'crazy', 'mad', 'nested', 'dest') return testSuccess(src, dest, done) }) it("should error when dest is 'src/dest'", done => { const dest = path.join(TEST_DIR, 'src', 'dest') return testError(src, dest, done) }) it("should error when dest is 'src/src_dest'", done => { const dest = path.join(TEST_DIR, 'src', 'src_dest') return testError(src, dest, done) }) it("should error when dest is 'src/dest_src'", done => { const dest = path.join(TEST_DIR, 'src', 'dest_src') return testError(src, dest, done) }) it("should error when dest is 'src/dest/src'", done => { const dest = path.join(TEST_DIR, 'src', 'dest', 'src') return testError(src, dest, done) }) }) describe('>> when dest is a symlink', () => { it('should error when dest points exactly to src and dereference is true', done => { const destLink = path.join(TEST_DIR, 'dest-symlink') fs.symlinkSync(src, destLink, 'dir') const srclenBefore = klawSync(src).length assert(srclenBefore > 2) fs.copy(src, destLink, { dereference: true }, err => { assert.strictEqual(err.message, 'Source and destination must not be the same.') const srclenAfter = klawSync(src).length assert.strictEqual(srclenAfter, srclenBefore, 'src length should not change') const link = fs.readlinkSync(destLink) assert.strictEqual(link, src) done() }) }) it('should error when dest is a subdirectory of src (bind-mounted directory with subdirectory)', done => { const destLink = path.join(TEST_DIR, 'dest-symlink') fs.symlinkSync(src, destLink, 'dir') const srclenBefore = klawSync(src).length assert(srclenBefore > 2) const dest = path.join(destLink, 'dir1') assert(fs.existsSync(dest)) fs.copy(src, dest, err => { assert.strictEqual(err.message, `Cannot copy '${src}' to a subdirectory of itself, '${dest}'.`) const srclenAfter = klawSync(src).length assert.strictEqual(srclenAfter, srclenBefore, 'src length should not change') const link = fs.readlinkSync(destLink) assert.strictEqual(link, src) done() }) }) it('should error when dest is a subdirectory of src (more than one level depth)', done => { const destLink = path.join(TEST_DIR, 'dest-symlink') fs.symlinkSync(src, destLink, 'dir') const srclenBefore = klawSync(src).length assert(srclenBefore > 2) const dest = path.join(destLink, 'dir1', 'dir2') assert(fs.existsSync(dest)) fs.copy(src, dest, err => { assert.strictEqual(err.message, `Cannot copy '${src}' to a subdirectory of itself, '${path.join(destLink, 'dir1')}'.`) const srclenAfter = klawSync(src).length assert.strictEqual(srclenAfter, srclenBefore, 'src length should not change') const link = fs.readlinkSync(destLink) assert.strictEqual(link, src) done() }) }) it('should copy the directory successfully when src is a subdir of resolved dest path and dereference is true', done => { const srcInDest = path.join(TEST_DIR, 'dest', 'some', 'nested', 'src') const destLink = path.join(TEST_DIR, 'dest-symlink') fs.copySync(src, srcInDest) // put some stuff in srcInDest const dest = path.join(TEST_DIR, 'dest') fs.symlinkSync(dest, destLink, 'dir') const srclen = klawSync(srcInDest).length const destlenBefore = klawSync(dest).length assert(srclen > 2) fs.copy(srcInDest, destLink, { dereference: true }, err => { assert.ifError(err) const destlenAfter = klawSync(dest).length // assert dest length is oldlen + length of stuff copied from src assert.strictEqual(destlenAfter, destlenBefore + srclen, 'dest length should be equal to old length + copied legnth') FILES.forEach(f => assert(fs.existsSync(path.join(dest, f)), 'file copied')) const o0 = fs.readFileSync(path.join(dest, FILES[0]), 'utf8') const o1 = fs.readFileSync(path.join(dest, FILES[1]), 'utf8') const o2 = fs.readFileSync(path.join(dest, FILES[2]), 'utf8') const o3 = fs.readFileSync(path.join(dest, FILES[3]), 'utf8') assert.strictEqual(o0, dat0, 'files contents matched') assert.strictEqual(o1, dat1, 'files contents matched') assert.strictEqual(o2, dat2, 'files contents matched') assert.strictEqual(o3, dat3, 'files contents matched') done() }) }) }) }) describe('> when source is a symlink', () => { describe('>> when dest is a directory', () => { it('should error when resolved src path points to dest', done => { const srcLink = path.join(TEST_DIR, 'src-symlink') fs.symlinkSync(src, srcLink, 'dir') const dest = path.join(TEST_DIR, 'src') fs.copy(srcLink, dest, err => { assert(err) // assert source not affected const link = fs.readlinkSync(srcLink) assert.strictEqual(link, src) done() }) }) it('should error when dest is a subdir of resolved src path', done => { const srcLink = path.join(TEST_DIR, 'src-symlink') fs.symlinkSync(src, srcLink, 'dir') const dest = path.join(TEST_DIR, 'src', 'some', 'nested', 'dest') fs.mkdirsSync(dest) fs.copy(srcLink, dest, err => { assert(err) const link = fs.readlinkSync(srcLink) assert.strictEqual(link, src) done() }) }) it('should error when resolved src path is a subdir of dest', done => { const dest = path.join(TEST_DIR, 'dest') const resolvedSrcPath = path.join(dest, 'contains', 'src') const srcLink = path.join(TEST_DIR, 'src-symlink') fs.copySync(src, resolvedSrcPath) // make symlink that points to a subdir in dest fs.symlinkSync(resolvedSrcPath, srcLink, 'dir') fs.copy(srcLink, dest, err => { assert(err) done() }) }) it("should copy the directory successfully when dest is 'src_src/dest'", done => { const srcLink = path.join(TEST_DIR, 'src-symlink') fs.symlinkSync(src, srcLink, 'dir') const dest = path.join(TEST_DIR, 'src_src', 'dest') testSuccess(srcLink, dest, () => { const link = fs.readlinkSync(dest) assert.strictEqual(link, src) done() }) }) it("should copy the directory successfully when dest is 'srcsrc/dest'", done => { const srcLink = path.join(TEST_DIR, 'src-symlink') fs.symlinkSync(src, srcLink, 'dir') const dest = path.join(TEST_DIR, 'srcsrc', 'dest') testSuccess(srcLink, dest, () => { const link = fs.readlinkSync(dest) assert.strictEqual(link, src) done() }) }) }) describe('>> when dest is a symlink', () => { it('should error when resolved dest path is exactly the same as resolved src path and dereference is true', done => { const srcLink = path.join(TEST_DIR, 'src-symlink') fs.symlinkSync(src, srcLink, 'dir') const destLink = path.join(TEST_DIR, 'dest-symlink') fs.symlinkSync(src, destLink, 'dir') const srclenBefore = klawSync(srcLink).length const destlenBefore = klawSync(destLink).length assert(srclenBefore > 2) assert(destlenBefore > 2) fs.copy(srcLink, destLink, { dereference: true }, err => { assert.strictEqual(err.message, 'Source and destination must not be the same.') const srclenAfter = klawSync(srcLink).length assert.strictEqual(srclenAfter, srclenBefore, 'src length should not change') const destlenAfter = klawSync(destLink).length assert.strictEqual(destlenAfter, destlenBefore, 'dest length should not change') const srcln = fs.readlinkSync(srcLink) assert.strictEqual(srcln, src) const destln = fs.readlinkSync(destLink) assert.strictEqual(destln, src) done() }) }) it('should error when resolved dest path is a subdir of resolved src path', done => { const srcLink = path.join(TEST_DIR, 'src-symlink') fs.symlinkSync(src, srcLink, 'dir') const destLink = path.join(TEST_DIR, 'dest-symlink') const resolvedDestPath = path.join(TEST_DIR, 'src', 'some', 'nested', 'dest') fs.ensureFileSync(path.join(resolvedDestPath, 'subdir', 'somefile.txt')) fs.symlinkSync(resolvedDestPath, destLink, 'dir') fs.copy(srcLink, destLink, err => { assert.strictEqual(err.message, `Cannot copy '${src}' to a subdirectory of itself, '${resolvedDestPath}'.`) const destln = fs.readlinkSync(destLink) assert.strictEqual(destln, resolvedDestPath) done() }) }) }) }) }) function testSuccess (src, dest, done) { const srclen = klawSync(src).length assert(srclen > 2) fs.copy(src, dest, err => { assert.ifError(err) FILES.forEach(f => assert(fs.existsSync(path.join(dest, f)), 'file copied')) const o0 = fs.readFileSync(path.join(dest, FILES[0]), 'utf8') const o1 = fs.readFileSync(path.join(dest, FILES[1]), 'utf8') const o2 = fs.readFileSync(path.join(dest, FILES[2]), 'utf8') const o3 = fs.readFileSync(path.join(dest, FILES[3]), 'utf8') assert.strictEqual(o0, dat0, 'file contents matched') assert.strictEqual(o1, dat1, 'file contents matched') assert.strictEqual(o2, dat2, 'file contents matched') assert.strictEqual(o3, dat3, 'file contents matched') done() }) } function testError (src, dest, done) { fs.copy(src, dest, err => { assert.strictEqual(err.message, `Cannot copy '${src}' to a subdirectory of itself, '${dest}'.`) done() }) } ================================================ FILE: lib/copy/__tests__/copy-readonly-dir.test.js ================================================ 'use strict' // relevant: https://github.com/jprichardson/node-fs-extra/issues/599 const fs = require('../../') const os = require('os') const fse = require('../../') const path = require('path') const assert = require('assert') const klawSync = require('klaw-sync') /* global afterEach, beforeEach, describe, it */ let TEST_DIR = '' const FILES = [ path.join('dir1', 'file1.txt'), path.join('dir1', 'dir2', 'file2.txt'), path.join('dir1', 'dir2', 'dir3', 'file3.txt') ] describe('+ copy() - copy a readonly directory with content', () => { beforeEach(done => { TEST_DIR = path.join(os.tmpdir(), 'test', 'fs-extra', 'copy-readonly-dir') fse.emptyDir(TEST_DIR, done) }) afterEach(done => { klawSync(TEST_DIR).forEach(data => fs.chmodSync(data.path, 0o777)) fse.remove(TEST_DIR, done) }) describe('> when src is readonly directory with content', () => { it('should copy successfully', done => { FILES.forEach(file => { fs.outputFileSync(path.join(TEST_DIR, file), file) }) const sourceDir = path.join(TEST_DIR, 'dir1') const sourceHierarchy = klawSync(sourceDir) sourceHierarchy.forEach(source => fs.chmodSync(source.path, source.stats.isDirectory() ? 0o555 : 0o444)) const targetDir = path.join(TEST_DIR, 'target') fse.copy(sourceDir, targetDir, err => { assert.ifError(err) // Make sure copy was made and mode was preserved assert(fs.existsSync(targetDir)) const targetHierarchy = klawSync(targetDir) assert(targetHierarchy.length === sourceHierarchy.length) targetHierarchy.forEach(target => assert(target.stats.mode === target.stats.isDirectory() ? 0o555 : 0o444)) done() }) }) }) }) ================================================ FILE: lib/copy/__tests__/copy-symlink-same-target.test.js ================================================ 'use strict' const os = require('os') const fs = require('../..') const path = require('path') const assert = require('assert') /* global afterEach, beforeEach, describe, it */ describe('copy() / symlink same target', () => { const TEST_DIR = path.join(os.tmpdir(), 'fs-extra', 'copy-symlink-same-target') beforeEach(done => { fs.emptyDir(TEST_DIR, done) }) afterEach(done => { fs.remove(TEST_DIR, done) }) describe('> when copying directory containing symlink', () => { it('should copy symlink when dest has no existing symlink', done => { const target = path.join(TEST_DIR, 'target') const src = path.join(TEST_DIR, 'src') const dest = path.join(TEST_DIR, 'dest') // Setup fs.mkdirpSync(target) fs.writeFileSync(path.join(target, 'file.txt'), 'content') fs.mkdirpSync(src) fs.symlinkSync(target, path.join(src, 'link'), 'dir') // Copy fs.copy(src, dest, err => { assert.ifError(err) // Verify symlink was copied const destLink = path.join(dest, 'link') assert.ok(fs.lstatSync(destLink).isSymbolicLink()) assert.strictEqual(fs.readlinkSync(destLink), target) done() }) }) // Also tests issue #1027 it('should overwrite symlink when dest has existing symlink pointing to SAME target', done => { const target = path.join(TEST_DIR, 'target') const src = path.join(TEST_DIR, 'src') const dest = path.join(TEST_DIR, 'dest') // Setup fs.mkdirpSync(target) fs.writeFileSync(path.join(target, 'file.txt'), 'content') fs.mkdirpSync(src) fs.mkdirpSync(dest) // Create symlinks pointing to the same target fs.symlinkSync(target, path.join(src, 'link'), 'dir') fs.symlinkSync(target, path.join(dest, 'link'), 'dir') // Copy should work - two different symlinks pointing to same target are NOT the same file fs.copy(src, dest) .then(() => { // Verify symlink was copied/overwritten const destLink = path.join(dest, 'link') assert.ok(fs.lstatSync(destLink).isSymbolicLink()) assert.strictEqual(fs.readlinkSync(destLink), target) done() }) .catch(done) }) it('should overwrite symlink when dest has existing symlink pointing to DIFFERENT target', done => { const target1 = path.join(TEST_DIR, 'target1') const target2 = path.join(TEST_DIR, 'target2') const src = path.join(TEST_DIR, 'src') const dest = path.join(TEST_DIR, 'dest') // Setup fs.mkdirpSync(target1) fs.mkdirpSync(target2) fs.writeFileSync(path.join(target1, 'file.txt'), 'content1') fs.writeFileSync(path.join(target2, 'file.txt'), 'content2') fs.mkdirpSync(src) fs.mkdirpSync(dest) // Create symlinks pointing to different targets fs.symlinkSync(target1, path.join(src, 'link'), 'dir') fs.symlinkSync(target2, path.join(dest, 'link'), 'dir') // Copy should work fs.copy(src, dest, err => { assert.ifError(err) // Verify symlink was copied/overwritten to point to target1 const destLink = path.join(dest, 'link') assert.ok(fs.lstatSync(destLink).isSymbolicLink()) assert.strictEqual(fs.readlinkSync(destLink), target1) done() }) }) }) describe('> when copying file symlinks', () => { it('should overwrite file symlink when dest has existing symlink pointing to SAME target', done => { const target = path.join(TEST_DIR, 'target.txt') const src = path.join(TEST_DIR, 'src') const dest = path.join(TEST_DIR, 'dest') // Setup fs.writeFileSync(target, 'content') fs.mkdirpSync(src) fs.mkdirpSync(dest) // Create file symlinks pointing to the same target fs.symlinkSync(target, path.join(src, 'link'), 'file') fs.symlinkSync(target, path.join(dest, 'link'), 'file') // Copy should work fs.copy(src, dest) .then(() => { // Verify symlink was copied/overwritten const destLink = path.join(dest, 'link') assert.ok(fs.lstatSync(destLink).isSymbolicLink()) assert.strictEqual(fs.readlinkSync(destLink), target) done() }) .catch(done) }) it('should overwrite file symlink when dest has existing symlink pointing to DIFFERENT target', done => { const target1 = path.join(TEST_DIR, 'target1.txt') const target2 = path.join(TEST_DIR, 'target2.txt') const src = path.join(TEST_DIR, 'src') const dest = path.join(TEST_DIR, 'dest') // Setup fs.writeFileSync(target1, 'content1') fs.writeFileSync(target2, 'content2') fs.mkdirpSync(src) fs.mkdirpSync(dest) // Create file symlinks pointing to different targets fs.symlinkSync(target1, path.join(src, 'link'), 'file') fs.symlinkSync(target2, path.join(dest, 'link'), 'file') // Copy should work fs.copy(src, dest, err => { assert.ifError(err) // Verify symlink was copied/overwritten to point to target1 const destLink = path.join(dest, 'link') assert.ok(fs.lstatSync(destLink).isSymbolicLink()) assert.strictEqual(fs.readlinkSync(destLink), target1) done() }) }) }) describe('> when copying symlink directly to another symlink (issue #1019)', () => { it('should copy symlink to another symlink pointing to same target', done => { const target = path.join(TEST_DIR, 'target.txt') const srcLink = path.join(TEST_DIR, 'srcLink') const destLink = path.join(TEST_DIR, 'destLink') // Setup - two different symlinks pointing to the same file fs.writeFileSync(target, 'content') fs.symlinkSync(target, srcLink, 'file') fs.symlinkSync(target, destLink, 'file') // Copy should work - these are different symlinks even though they point to the same target fs.copy(srcLink, destLink) .then(() => { assert.ok(fs.lstatSync(destLink).isSymbolicLink()) assert.strictEqual(fs.readlinkSync(destLink), target) done() }) .catch(done) }) }) describe('> edge cases', () => { it('should still prevent copying a symlink to itself', done => { const target = path.join(TEST_DIR, 'target') const link = path.join(TEST_DIR, 'link') // Setup fs.mkdirpSync(target) fs.symlinkSync(target, link, 'dir') // Copying a symlink to itself should fail fs.copy(link, link) .then(() => { done(new Error('Expected error to be thrown')) }) .catch(err => { assert.strictEqual(err.message, 'Source and destination must not be the same.') done() }) }) it('should allow copying symlink to subdirectory of its target (symlink copy, not recursive)', done => { // When copying a symlink (not dereferencing), we just copy the link itself // This should be allowed because we're not recursively copying the target's contents const target = path.join(TEST_DIR, 'target') const src = path.join(TEST_DIR, 'src') // Setup fs.mkdirpSync(target) fs.mkdirpSync(path.join(target, 'subdir')) fs.mkdirpSync(src) fs.symlinkSync(target, path.join(src, 'link'), 'dir') // Dest is inside src's resolved target const dest = path.join(target, 'subdir', 'dest') // This should work - we're just copying the symlink, not following it fs.copy(src, dest) .then(() => { // Verify symlink was copied const destLink = path.join(dest, 'link') assert.ok(fs.lstatSync(destLink).isSymbolicLink()) assert.strictEqual(fs.readlinkSync(destLink), target) done() }) .catch(done) }) }) }) ================================================ FILE: lib/copy/__tests__/copy-sync-broken-symlink.test.js ================================================ 'use strict' const fs = require('fs') const os = require('os') const fse = require('../..') const path = require('path') const assert = require('assert') const copySync = require('../copy-sync') /* global afterEach, beforeEach, describe, it */ describe('copy-sync / broken symlink', () => { const TEST_DIR = path.join(os.tmpdir(), 'fs-extra', 'copy-sync-broken-symlink') const src = path.join(TEST_DIR, 'src') const dest = path.join(TEST_DIR, 'dest') beforeEach(done => { fse.emptyDir(TEST_DIR, err => { assert.ifError(err) createFixtures(src, done) }) }) afterEach(done => fse.remove(TEST_DIR, done)) describe('when symlink is broken', () => { it('should not throw error if dereference is false', () => { let err = null try { copySync(src, dest) } catch (e) { err = e } assert.strictEqual(err, null) }) it('should throw error if dereference is true', () => { assert.throws(() => copySync(src, dest, { dereference: true }), err => err.code === 'ENOENT') }) }) }) function createFixtures (srcDir, callback) { fs.mkdir(srcDir, err => { let brokenFile let brokenFileLink if (err) return callback(err) try { brokenFile = path.join(srcDir, 'does-not-exist') brokenFileLink = path.join(srcDir, 'broken-symlink') fs.writeFileSync(brokenFile, 'does not matter') fs.symlinkSync(brokenFile, brokenFileLink, 'file') } catch (err) { callback(err) } // break the symlink now fse.remove(brokenFile, callback) }) } ================================================ FILE: lib/copy/__tests__/copy-sync-case-insensitive-paths.test.js ================================================ 'use strict' const assert = require('assert') const os = require('os') const path = require('path') const fs = require('../../') const platform = os.platform() /* global beforeEach, afterEach, describe, it */ describe('+ copySync() - case insensitive paths', () => { let TEST_DIR = '' let src = '' let dest = '' beforeEach(done => { TEST_DIR = path.join(os.tmpdir(), 'fs-extra', 'copy-sync-case-insensitive-paths') fs.emptyDir(TEST_DIR, done) }) afterEach(() => fs.removeSync(TEST_DIR)) describe('> when src is a directory', () => { it('should behave correctly based on the OS', () => { src = path.join(TEST_DIR, 'srcdir') fs.outputFileSync(path.join(src, 'subdir', 'file.txt'), 'some data') dest = path.join(TEST_DIR, 'srcDir') let errThrown = false try { fs.copySync(src, dest) } catch (err) { if (platform === 'darwin' || platform === 'win32') { assert.strictEqual(err.message, 'Source and destination must not be the same.') errThrown = true } } if (platform === 'darwin' || platform === 'win32') assert(errThrown) if (platform === 'linux') { assert(fs.existsSync(dest)) assert.strictEqual(fs.readFileSync(path.join(dest, 'subdir', 'file.txt'), 'utf8'), 'some data') assert(!errThrown) } }) }) describe('> when src is a file', () => { it('should behave correctly based on the OS', () => { src = path.join(TEST_DIR, 'srcfile') fs.outputFileSync(src, 'some data') dest = path.join(TEST_DIR, 'srcFile') let errThrown = false try { fs.copySync(src, dest) } catch (err) { if (platform === 'darwin' || platform === 'win32') { assert.strictEqual(err.message, 'Source and destination must not be the same.') errThrown = true } } if (platform === 'darwin' || platform === 'win32') assert(errThrown) if (platform === 'linux') { assert(fs.existsSync(dest)) assert.strictEqual(fs.readFileSync(dest, 'utf8'), 'some data') assert(!errThrown) } }) }) describe('> when src is a symlink', () => { it('should behave correctly based on the OS, symlink dir', () => { src = path.join(TEST_DIR, 'srcdir') fs.outputFileSync(path.join(src, 'subdir', 'file.txt'), 'some data') const srcLink = path.join(TEST_DIR, 'src-symlink') fs.symlinkSync(src, srcLink, 'dir') dest = path.join(TEST_DIR, 'src-Symlink') let errThrown = false try { fs.copySync(srcLink, dest) } catch (err) { if (platform === 'darwin' || platform === 'win32') { assert.strictEqual(err.message, 'Source and destination must not be the same.') errThrown = true } } if (platform === 'darwin' || platform === 'win32') assert(errThrown) if (platform === 'linux') { assert(fs.existsSync(dest)) assert.strictEqual(fs.readFileSync(path.join(dest, 'subdir', 'file.txt'), 'utf8'), 'some data') const destLink = fs.readlinkSync(dest) assert.strictEqual(destLink, src) assert(!errThrown) } }) it('should behave correctly based on the OS, symlink file', () => { src = path.join(TEST_DIR, 'srcfile') fs.outputFileSync(src, 'some data') const srcLink = path.join(TEST_DIR, 'src-symlink') fs.symlinkSync(src, srcLink, 'file') dest = path.join(TEST_DIR, 'src-Symlink') let errThrown = false try { fs.copySync(srcLink, dest) } catch (err) { if (platform === 'darwin' || platform === 'win32') { assert.strictEqual(err.message, 'Source and destination must not be the same.') errThrown = true } } if (platform === 'darwin' || platform === 'win32') assert(errThrown) if (platform === 'linux') { assert(fs.existsSync(dest)) assert.strictEqual(fs.readFileSync(dest, 'utf8'), 'some data') const destLink = fs.readlinkSync(dest) assert.strictEqual(destLink, src) assert(!errThrown) } }) }) }) ================================================ FILE: lib/copy/__tests__/copy-sync-dir.test.js ================================================ 'use strict' const fs = require('../../') const os = require('os') const path = require('path') const assert = require('assert') const crypto = require('crypto') /* global beforeEach, afterEach, describe, it */ describe('+ copySync() / dir', () => { const SIZE = 16 * 64 * 1024 + 7 let TEST_DIR let src, dest beforeEach(done => { TEST_DIR = path.join(os.tmpdir(), 'fs-extra', 'copy-sync-dir') src = path.join(TEST_DIR, 'src') dest = path.join(TEST_DIR, 'dest') fs.emptyDir(TEST_DIR, done) }) afterEach(done => fs.remove(TEST_DIR, done)) describe('> when src is a directory', () => { describe('> when dest exists and is a file', () => { it('should throw error', () => { const src = path.join(TEST_DIR, 'src') const dest = path.join(TEST_DIR, 'file.txt') fs.mkdirSync(src) fs.ensureFileSync(dest) try { fs.copySync(src, dest) } catch (err) { assert.strictEqual(err.message, `Cannot overwrite non-directory '${dest}' with directory '${src}'.`) } }) }) it('should copy the directory synchronously', () => { const FILES = 2 src = path.join(TEST_DIR, 'src') dest = path.join(TEST_DIR, 'dest') fs.mkdirSync(src) for (let i = 0; i < FILES; ++i) { fs.writeFileSync(path.join(src, i.toString()), crypto.randomBytes(SIZE)) } const subdir = path.join(src, 'subdir') fs.mkdirSync(subdir) for (let i = 0; i < FILES; ++i) { fs.writeFileSync(path.join(subdir, i.toString()), crypto.randomBytes(SIZE)) } fs.copySync(src, dest) assert(fs.existsSync(dest)) for (let i = 0; i < FILES; ++i) { assert(fs.existsSync(path.join(dest, i.toString()))) } const destSub = path.join(dest, 'subdir') for (let j = 0; j < FILES; ++j) { assert(fs.existsSync(path.join(destSub, j.toString()))) } }) it('should preserve symbolic links', () => { const srcTarget = path.join(TEST_DIR, 'destination') fs.mkdirSync(src) fs.mkdirSync(srcTarget) fs.symlinkSync(srcTarget, path.join(src, 'symlink'), 'dir') fs.copySync(src, dest) const link = fs.readlinkSync(path.join(dest, 'symlink')) assert.strictEqual(link, srcTarget) }) describe('> when the destination dir does not exist', () => { it('should create the destination directory and copy the file', () => { const src = path.join(TEST_DIR, 'data/') fs.mkdirSync(src) const d1 = 'file1' const d2 = 'file2' fs.writeFileSync(path.join(src, 'f1.txt'), d1) fs.writeFileSync(path.join(src, 'f2.txt'), d2) const dest = path.join(TEST_DIR, 'this/path/does/not/exist/outputDir') fs.copySync(src, dest) const o1 = fs.readFileSync(path.join(dest, 'f1.txt'), 'utf8') const o2 = fs.readFileSync(path.join(dest, 'f2.txt'), 'utf8') assert.strictEqual(d1, o1) assert.strictEqual(d2, o2) }) }) }) describe('> when filter is used', () => { it('should do nothing if filter fails', () => { const srcDir = path.join(TEST_DIR, 'src') const srcFile = path.join(srcDir, 'srcfile.css') fs.outputFileSync(srcFile, 'src contents') const destDir = path.join(TEST_DIR, 'dest') const destFile = path.join(destDir, 'destfile.css') const filter = s => path.extname(s) !== '.css' && !fs.statSync(s).isDirectory() fs.copySync(srcFile, destFile, filter) assert(!fs.existsSync(destDir)) }) it('should apply filter recursively', () => { const FILES = 2 // Don't match anything that ends with a digit higher than 0: const filter = s => /(0|\D)$/i.test(s) fs.mkdirSync(src) for (let i = 0; i < FILES; ++i) { fs.writeFileSync(path.join(src, i.toString()), crypto.randomBytes(SIZE)) } const subdir = path.join(src, 'subdir') fs.mkdirSync(subdir) for (let i = 0; i < FILES; ++i) { fs.writeFileSync(path.join(subdir, i.toString()), crypto.randomBytes(SIZE)) } fs.copySync(src, dest, filter) assert(fs.existsSync(dest)) assert(FILES > 1) for (let i = 0; i < FILES; ++i) { if (i === 0) { assert(fs.existsSync(path.join(dest, i.toString()))) } else { assert(!fs.existsSync(path.join(dest, i.toString()))) } } const destSub = path.join(dest, 'subdir') for (let j = 0; j < FILES; ++j) { if (j === 0) { assert(fs.existsSync(path.join(destSub, j.toString()))) } else { assert(!fs.existsSync(path.join(destSub, j.toString()))) } } }) it('should apply the filter to directory names', () => { const IGNORE = 'ignore' const filter = p => !~p.indexOf(IGNORE) fs.mkdirSync(src) const ignoreDir = path.join(src, IGNORE) fs.mkdirSync(ignoreDir) fs.writeFileSync(path.join(ignoreDir, 'file'), crypto.randomBytes(SIZE)) fs.copySync(src, dest, filter) assert(!fs.existsSync(path.join(dest, IGNORE)), 'directory was not ignored') assert(!fs.existsSync(path.join(dest, IGNORE, 'file')), 'file was not ignored') }) it('should apply filter when it is applied only to dest', done => { const timeCond = new Date().getTime() const filter = (s, d) => fs.statSync(d).mtime.getTime() < timeCond const dest = path.join(TEST_DIR, 'dest') setTimeout(() => { fs.outputFileSync(path.join(src, 'somefile.html'), 'some data') fs.mkdirSync(dest) fs.copySync(src, dest, filter) assert(!fs.existsSync(path.join(dest, 'somefile.html'))) done() }, 1000) }) it('should apply filter when it is applied to both src and dest', done => { const timeCond = new Date().getTime() const filter = (s, d) => s.split('.').pop() !== 'css' && fs.statSync(path.dirname(d)).mtime.getTime() > timeCond const dest = path.join(TEST_DIR, 'dest') setTimeout(() => { const srcFile1 = path.join(TEST_DIR, '1.html') const srcFile2 = path.join(TEST_DIR, '2.css') const srcFile3 = path.join(TEST_DIR, '3.jade') fs.writeFileSync(srcFile1, '') fs.writeFileSync(srcFile2, '') fs.writeFileSync(srcFile3, '') const destFile1 = path.join(dest, 'dest1.html') const destFile2 = path.join(dest, 'dest2.css') const destFile3 = path.join(dest, 'dest3.jade') fs.mkdirSync(dest) fs.copySync(srcFile1, destFile1, filter) fs.copySync(srcFile2, destFile2, filter) fs.copySync(srcFile3, destFile3, filter) assert(fs.existsSync(destFile1)) assert(!fs.existsSync(destFile2)) assert(fs.existsSync(destFile3)) done() }, 1000) }) }) }) ================================================ FILE: lib/copy/__tests__/copy-sync-file.test.js ================================================ 'use strict' const fs = require('../../') const os = require('os') const path = require('path') const assert = require('assert') const crypto = require('crypto') /* global afterEach, beforeEach, describe, it */ const SIZE = 16 * 64 * 1024 + 7 describe('+ copySync() / file', () => { let TEST_DIR beforeEach(done => { TEST_DIR = path.join(os.tmpdir(), 'fs-extra', 'copy-sync-file') fs.emptyDir(TEST_DIR, done) }) afterEach(done => fs.remove(TEST_DIR, done)) describe('> when src is a file', () => { describe('> when dest exists and is a directory', () => { it('should throw error', () => { const src = path.join(TEST_DIR, 'file.txt') const dest = path.join(TEST_DIR, 'dir') fs.ensureFileSync(src) fs.ensureDirSync(dest) try { fs.copySync(src, dest) } catch (err) { assert.strictEqual(err.message, `Cannot overwrite directory '${dest}' with non-directory '${src}'.`) } }) }) it('should copy the file synchronously', () => { const fileSrc = path.join(TEST_DIR, 'TEST_fs-extra_src') const fileDest = path.join(TEST_DIR, 'TEST_fs-extra_copy') fs.writeFileSync(fileSrc, crypto.randomBytes(SIZE)) const srcMd5 = crypto.createHash('md5').update(fs.readFileSync(fileSrc)).digest('hex') let destMd5 = '' fs.copySync(fileSrc, fileDest) destMd5 = crypto.createHash('md5').update(fs.readFileSync(fileDest)).digest('hex') assert.strictEqual(srcMd5, destMd5) }) it('should follow symlinks', () => { const fileSrc = path.join(TEST_DIR, 'TEST_fs-extra_src') const fileDest = path.join(TEST_DIR, 'TEST_fs-extra_copy') const linkSrc = path.join(TEST_DIR, 'TEST_fs-extra_copy_link') fs.writeFileSync(fileSrc, crypto.randomBytes(SIZE)) const srcMd5 = crypto.createHash('md5').update(fs.readFileSync(fileSrc)).digest('hex') let destMd5 = '' fs.symlinkSync(fileSrc, linkSrc) fs.copySync(linkSrc, fileDest) destMd5 = crypto.createHash('md5').update(fs.readFileSync(fileDest)).digest('hex') assert.strictEqual(srcMd5, destMd5) }) it('should maintain file mode', () => { const fileSrc = path.join(TEST_DIR, 'TEST_fs-extra_src') const fileDest = path.join(TEST_DIR, 'TEST_fs-extra_copy') fs.writeFileSync(fileSrc, crypto.randomBytes(SIZE)) fs.chmodSync(fileSrc, 0o750) fs.copySync(fileSrc, fileDest) const statSrc = fs.statSync(fileSrc) const statDest = fs.statSync(fileDest) assert.strictEqual(statSrc.mode, statDest.mode) }) it('should only copy files allowed by filter fn', () => { const srcFile1 = path.join(TEST_DIR, '1.html') const srcFile2 = path.join(TEST_DIR, '2.css') const srcFile3 = path.join(TEST_DIR, '3.jade') fs.writeFileSync(srcFile1, '') fs.writeFileSync(srcFile2, '') fs.writeFileSync(srcFile3, '') const destFile1 = path.join(TEST_DIR, 'dest1.html') const destFile2 = path.join(TEST_DIR, 'dest2.css') const destFile3 = path.join(TEST_DIR, 'dest3.jade') const filter = s => s.split('.').pop() !== 'css' fs.copySync(srcFile1, destFile1, filter) fs.copySync(srcFile2, destFile2, filter) fs.copySync(srcFile3, destFile3, filter) assert(fs.existsSync(destFile1)) assert(!fs.existsSync(destFile2)) assert(fs.existsSync(destFile3)) }) it('should not call filter fn more than needed', () => { const src = path.join(TEST_DIR, 'foo') fs.writeFileSync(src, '') const dest = path.join(TEST_DIR, 'bar') let filterCallCount = 0 const filter = () => { filterCallCount++ return true } fs.copySync(src, dest, filter) assert.strictEqual(filterCallCount, 1) assert(fs.existsSync(dest)) }) describe('> when the destination dir does not exist', () => { it('should create the destination directory and copy the file', () => { const src = path.join(TEST_DIR, 'file.txt') const dest = path.join(TEST_DIR, 'this/path/does/not/exist/copied.txt') const data = 'did it copy?\n' fs.writeFileSync(src, data, 'utf8') fs.copySync(src, dest) const data2 = fs.readFileSync(dest, 'utf8') assert.strictEqual(data, data2) }) }) describe('> when src file does not have write permissions', () => { it('should be able to copy contents of file', () => { const fileSrc = path.join(TEST_DIR, 'file.txt') const fileDest = path.join(TEST_DIR, 'file-copy.txt') const data = 'did it copy?' fs.writeFileSync(fileSrc, data, 'utf8') fs.chmodSync(fileSrc, '0444') fs.copySync(fileSrc, fileDest) const data2 = fs.readFileSync(fileDest, 'utf8') assert.strictEqual(data, data2) }) }) describe('> when overwrite option is passed', () => { const srcData = 'some src data' let src, dest beforeEach(() => { src = path.join(TEST_DIR, 'src-file') dest = path.join(TEST_DIR, 'des-file') // source file must always exist in these cases fs.writeFileSync(src, srcData) }) describe('> when destination file does NOT exist', () => { describe('> when overwrite is true', () => { it('should copy the file and not throw an error', () => { fs.copySync(src, dest, { overwrite: true }) const destData = fs.readFileSync(dest, 'utf8') assert.strictEqual(srcData, destData) }) }) describe('> when overwrite is false', () => { it('should copy the file and not throw an error', () => { fs.copySync(src, dest, { overwrite: false }) const destData = fs.readFileSync(dest, 'utf8') assert.strictEqual(srcData, destData) }) }) }) describe('when destination file does exist', () => { let destData beforeEach(() => { destData = 'some dest data' fs.writeFileSync(dest, destData) }) describe('> when overwrite is true', () => { it('should copy the file and not throw an error', () => { fs.copySync(src, dest, { overwrite: true }) destData = fs.readFileSync(dest, 'utf8') assert.strictEqual(srcData, destData) }) }) describe('> when overwrite is false', () => { it('should not throw an error', () => { fs.copySync(src, dest, { overwrite: false }) // copy never happened const destDataNew = fs.readFileSync(dest, 'utf8') assert.strictEqual(destData, destDataNew) }) it('should throw an error when errorOnExist is true', () => { assert.throws(() => fs.copySync(src, dest, { overwrite: false, errorOnExist: true })) // copy never happened const destDataNew = fs.readFileSync(dest, 'utf8') assert.strictEqual(destData, destDataNew) }) }) describe('> when overwrite is true and dest is readonly', () => { it('should copy the file and not throw an error', () => { try { fs.chmodSync(dest, 0o444) fs.copySync(src, dest, { overwrite: true }) destData = fs.readFileSync(dest, 'utf8') assert.strictEqual(srcData, destData) } finally { // destination file is readonly so just remove it so we don't affect other tests fs.unlinkSync(dest) } }) }) }) }) describe('clobber', () => { let src, dest, srcData, destData beforeEach(() => { src = path.join(TEST_DIR, 'src-file') dest = path.join(TEST_DIR, 'des-file') srcData = 'some src data' destData = 'some dest data' fs.writeFileSync(src, srcData) fs.writeFileSync(dest, destData) }) it('is an alias for overwrite', () => { fs.copySync(src, dest, { clobber: false }) // copy never happened const destDataNew = fs.readFileSync(dest, 'utf8') assert.strictEqual(destData, destDataNew) }) }) }) }) ================================================ FILE: lib/copy/__tests__/copy-sync-preserve-timestamp.test.js ================================================ 'use strict' const fs = require('../../') const os = require('os') const path = require('path') const copySync = require('../copy-sync') const utimesSync = require('../../util/utimes').utimesMillisSync const assert = require('assert') /* global beforeEach, afterEach, describe, it */ if (process.arch === 'ia32') console.warn('32 bit arch; skipping copySync timestamp tests') const describeIfPractical = process.arch === 'ia32' ? describe.skip : describe describeIfPractical('copySync() - preserveTimestamps option', () => { let TEST_DIR, SRC, DEST, FILES function setupFixture (readonly) { TEST_DIR = path.join(os.tmpdir(), 'fs-extra', 'copy-sync-preserve-timestamp') SRC = path.join(TEST_DIR, 'src') DEST = path.join(TEST_DIR, 'dest') FILES = ['a-file', path.join('a-folder', 'another-file'), path.join('a-folder', 'another-folder', 'file3')] const timestamp = Date.now() / 1000 - 5 FILES.forEach(f => { const filePath = path.join(SRC, f) fs.ensureFileSync(filePath) // rewind timestamps to make sure that coarser OS timestamp resolution // does not alter results utimesSync(filePath, timestamp, timestamp) if (readonly) { fs.chmodSync(filePath, 0o444) } }) } afterEach(done => fs.remove(TEST_DIR, done)) describe('> when preserveTimestamps option is true', () => { ;[ { subcase: 'writable', readonly: false }, { subcase: 'readonly', readonly: true } ].forEach(params => { describe(`>> with ${params.subcase} source files`, () => { beforeEach(() => setupFixture(params.readonly)) it('should have the same timestamps on copy', () => { copySync(SRC, DEST, { preserveTimestamps: true }) FILES.forEach(testFile({ preserveTimestamps: true })) }) }) }) }) function testFile (options) { return function (file) { const a = path.join(SRC, file) const b = path.join(DEST, file) const fromStat = fs.statSync(a) const toStat = fs.statSync(b) if (options.preserveTimestamps) { // Windows sub-second precision fixed: https://github.com/nodejs/io.js/issues/2069 assert.strictEqual(toStat.mtime.getTime(), fromStat.mtime.getTime(), 'different mtime values') assert.strictEqual(toStat.atime.getTime(), fromStat.atime.getTime(), 'different atime values') } else { // the access time might actually be the same, so check only modification time assert.notStrictEqual(toStat.mtime.getTime(), fromStat.mtime.getTime(), 'same mtime values') } } } }) ================================================ FILE: lib/copy/__tests__/copy-sync-prevent-copying-identical.test.js ================================================ 'use strict' const assert = require('assert') const os = require('os') const path = require('path') const fs = require('../../') const klawSync = require('klaw-sync') /* global beforeEach, afterEach, describe, it */ describe('+ copySync() - prevent copying identical files and dirs', () => { let TEST_DIR = '' let src = '' let dest = '' beforeEach(done => { TEST_DIR = path.join(os.tmpdir(), 'fs-extra', 'copy-sync-prevent-copying-identical') fs.emptyDir(TEST_DIR, done) }) afterEach(done => fs.remove(TEST_DIR, done)) it('should return an error if src and dest are the same', () => { const fileSrc = path.join(TEST_DIR, 'TEST_fs-extra_copy_sync') const fileDest = path.join(TEST_DIR, 'TEST_fs-extra_copy_sync') fs.ensureFileSync(fileSrc) try { fs.copySync(fileSrc, fileDest) } catch (err) { assert.strictEqual(err.message, 'Source and destination must not be the same.') } }) describe('dest with parent symlink', () => { describe('first parent is symlink', () => { it('should error when src is file', () => { const src = path.join(TEST_DIR, 'a', 'file.txt') const dest = path.join(TEST_DIR, 'b', 'file.txt') const srcParent = path.join(TEST_DIR, 'a') const destParent = path.join(TEST_DIR, 'b') fs.ensureFileSync(src) fs.ensureSymlinkSync(srcParent, destParent, 'dir') try { fs.copySync(src, dest) } catch (err) { assert.strictEqual(err.message, 'Source and destination must not be the same.') } finally { assert(fs.existsSync(src)) } }) it('should error when src is directory', () => { const src = path.join(TEST_DIR, 'a', 'foo') const dest = path.join(TEST_DIR, 'b', 'foo') const srcParent = path.join(TEST_DIR, 'a') const destParent = path.join(TEST_DIR, 'b') fs.ensureDirSync(src) fs.ensureSymlinkSync(srcParent, destParent, 'dir') try { fs.copySync(src, dest) } catch (err) { assert.strictEqual(err.message, 'Source and destination must not be the same.') } finally { assert(fs.existsSync(src)) } }) }) describe('nested dest', () => { it('should error when src is file', () => { const src = path.join(TEST_DIR, 'a', 'dir', 'file.txt') const dest = path.join(TEST_DIR, 'b', 'dir', 'file.txt') const srcParent = path.join(TEST_DIR, 'a') const destParent = path.join(TEST_DIR, 'b') fs.ensureFileSync(src) fs.ensureSymlinkSync(srcParent, destParent, 'dir') try { fs.copySync(src, dest) } catch (err) { assert.strictEqual(err.message, 'Source and destination must not be the same.') } finally { assert(fs.existsSync(src)) } }) it('should error when src is directory', () => { const src = path.join(TEST_DIR, 'a', 'dir', 'foo') const dest = path.join(TEST_DIR, 'b', 'dir', 'foo') const srcParent = path.join(TEST_DIR, 'a') const destParent = path.join(TEST_DIR, 'b') fs.ensureDirSync(src) fs.ensureSymlinkSync(srcParent, destParent, 'dir') try { fs.copySync(src, dest) } catch (err) { assert.strictEqual(err.message, 'Source and destination must not be the same.') } finally { assert(fs.existsSync(src)) } }) }) }) // src is directory: // src is regular, dest is symlink // src is symlink, dest is regular // src is symlink, dest is symlink describe('> when src is a directory', () => { describe('>> when src is regular and dest is a symlink that points to src', () => { it('should error if dereference is true', () => { src = path.join(TEST_DIR, 'src') fs.mkdirsSync(src) const subdir = path.join(TEST_DIR, 'src', 'subdir') fs.mkdirsSync(subdir) fs.writeFileSync(path.join(subdir, 'file.txt'), 'some data') const destLink = path.join(TEST_DIR, 'dest-symlink') fs.symlinkSync(src, destLink, 'dir') const oldlen = klawSync(src).length try { fs.copySync(src, destLink, { dereference: true }) } catch (err) { assert.strictEqual(err.message, 'Source and destination must not be the same.') } const newlen = klawSync(src).length assert.strictEqual(newlen, oldlen) const link = fs.readlinkSync(destLink) assert.strictEqual(link, src) }) }) describe('>> when src is a symlink that points to a regular dest', () => { it('should throw error', () => { dest = path.join(TEST_DIR, 'dest') fs.mkdirsSync(dest) const subdir = path.join(TEST_DIR, 'dest', 'subdir') fs.mkdirsSync(subdir) fs.writeFileSync(path.join(subdir, 'file.txt'), 'some data') const srcLink = path.join(TEST_DIR, 'src-symlink') fs.symlinkSync(dest, srcLink, 'dir') const oldlen = klawSync(dest).length try { fs.copySync(srcLink, dest) } catch (err) { assert(err) } // assert nothing copied const newlen = klawSync(dest).length assert.strictEqual(newlen, oldlen) const link = fs.readlinkSync(srcLink) assert.strictEqual(link, dest) }) }) describe('>> when src and dest are symlinks that point to the exact same path', () => { it('should error if src and dest are the same and dereferene is true', () => { src = path.join(TEST_DIR, 'src') fs.mkdirsSync(src) const srcLink = path.join(TEST_DIR, 'src_symlink') fs.symlinkSync(src, srcLink, 'dir') const destLink = path.join(TEST_DIR, 'dest_symlink') fs.symlinkSync(src, destLink, 'dir') const srclenBefore = klawSync(srcLink).length const destlenBefore = klawSync(destLink).length try { fs.copySync(srcLink, destLink, { dereference: true }) } catch (err) { assert.strictEqual(err.message, 'Source and destination must not be the same.') } const srclenAfter = klawSync(srcLink).length assert.strictEqual(srclenAfter, srclenBefore, 'src length should not change') const destlenAfter = klawSync(destLink).length assert.strictEqual(destlenAfter, destlenBefore, 'dest length should not change') const srcln = fs.readlinkSync(srcLink) assert.strictEqual(srcln, src) const destln = fs.readlinkSync(destLink) assert.strictEqual(destln, src) }) }) }) // src is file: // src is regular, dest is symlink // src is symlink, dest is regular // src is symlink, dest is symlink describe('> when src is a file', () => { describe('>> when src is regular and dest is a symlink that points to src', () => { it('should error if dereference is true', () => { src = path.join(TEST_DIR, 'src', 'somefile.txt') fs.ensureFileSync(src) fs.writeFileSync(src, 'some data') const destLink = path.join(TEST_DIR, 'dest-symlink') fs.symlinkSync(src, destLink, 'file') try { fs.copySync(src, destLink, { dereference: true }) } catch (err) { assert.strictEqual(err.message, 'Source and destination must not be the same.') } const link = fs.readlinkSync(destLink) assert.strictEqual(link, src) assert(fs.readFileSync(link, 'utf8'), 'some data') }) }) describe('>> when src is a symlink that points to a regular dest', () => { it('should throw error', () => { dest = path.join(TEST_DIR, 'dest', 'somefile.txt') fs.outputFileSync(dest, 'some data') const srcLink = path.join(TEST_DIR, 'src-symlink') fs.symlinkSync(dest, srcLink, 'file') try { fs.copySync(srcLink, dest) } catch (err) { assert.ok(err) } const link = fs.readlinkSync(srcLink) assert.strictEqual(link, dest) assert(fs.readFileSync(link, 'utf8'), 'some data') }) }) describe('>> when src and dest are symlinks that point to the exact same path', () => { it('should error if src and dest are the same and dereference is true', () => { src = path.join(TEST_DIR, 'src', 'srcfile.txt') fs.outputFileSync(src, 'src data') const srcLink = path.join(TEST_DIR, 'src_symlink') fs.symlinkSync(src, srcLink, 'file') const destLink = path.join(TEST_DIR, 'dest_symlink') fs.symlinkSync(src, destLink, 'file') try { fs.copySync(srcLink, destLink, { dereference: true }) } catch (err) { assert.strictEqual(err.message, 'Source and destination must not be the same.') } const srcln = fs.readlinkSync(srcLink) assert.strictEqual(srcln, src) const destln = fs.readlinkSync(destLink) assert.strictEqual(destln, src) assert(fs.readFileSync(srcln, 'utf8'), 'src data') assert(fs.readFileSync(destln, 'utf8'), 'src data') }) }) }) }) ================================================ FILE: lib/copy/__tests__/copy-sync-prevent-copying-into-itself.test.js ================================================ 'use strict' const assert = require('assert') const os = require('os') const path = require('path') const fs = require('../../') const klawSync = require('klaw-sync') /* global beforeEach, afterEach, describe, it */ // these files are used for all tests const FILES = [ 'file0.txt', path.join('dir1', 'file1.txt'), path.join('dir1', 'dir2', 'file2.txt'), path.join('dir1', 'dir2', 'dir3', 'file3.txt') ] const dat0 = 'file0' const dat1 = 'file1' const dat2 = 'file2' const dat3 = 'file3' describe('+ copySync() - prevent copying into itself', () => { let TEST_DIR, src beforeEach(done => { TEST_DIR = path.join(os.tmpdir(), 'fs-extra', 'copy-sync-prevent-copying-into-itself') src = path.join(TEST_DIR, 'src') fs.mkdirpSync(src) fs.outputFileSync(path.join(src, FILES[0]), dat0) fs.outputFileSync(path.join(src, FILES[1]), dat1) fs.outputFileSync(path.join(src, FILES[2]), dat2) fs.outputFileSync(path.join(src, FILES[3]), dat3) done() }) afterEach(done => fs.remove(TEST_DIR, done)) describe('> when source is a file', () => { it('should copy the file successfully even if dest parent is a subdir of src', () => { const srcFile = path.join(TEST_DIR, 'src', 'srcfile.txt') const destFile = path.join(TEST_DIR, 'src', 'dest', 'destfile.txt') fs.writeFileSync(srcFile, dat0) fs.copySync(srcFile, destFile) assert(fs.existsSync(destFile, 'file copied')) const out = fs.readFileSync(destFile, 'utf8') assert.strictEqual(out, dat0, 'file contents matched') }) }) // test for these cases: // - src is directory, dest is directory // - src is directory, dest is symlink // - src is symlink, dest is directory // - src is symlink, dest is symlink describe('> when source is a directory', () => { describe('>> when dest is a directory', () => { it('of not itself', () => { const dest = path.join(TEST_DIR, src.replace(/^\w:/, '')) return testSuccess(src, dest) }) it('of itself', () => { const dest = path.join(src, 'dest') return testError(src, dest) }) it("should copy the directory successfully when dest is 'src_dest'", () => { const dest = path.join(TEST_DIR, 'src_dest') return testSuccess(src, dest) }) it("should copy the directory successfully when dest is 'src-dest'", () => { const dest = path.join(TEST_DIR, 'src-dest') return testSuccess(src, dest) }) it("should copy the directory successfully when dest is 'dest_src'", () => { const dest = path.join(TEST_DIR, 'dest_src') return testSuccess(src, dest) }) it("should copy the directory successfully when dest is 'src_dest/src'", () => { const dest = path.join(TEST_DIR, 'src_dest', 'src') return testSuccess(src, dest) }) it("should copy the directory successfully when dest is 'src-dest/src'", () => { const dest = path.join(TEST_DIR, 'src-dest', 'src') return testSuccess(src, dest) }) it("should copy the directory successfully when dest is 'dest_src/src'", () => { const dest = path.join(TEST_DIR, 'dest_src', 'src') return testSuccess(src, dest) }) it("should copy the directory successfully when dest is 'src_src/dest'", () => { const dest = path.join(TEST_DIR, 'src_src', 'dest') return testSuccess(src, dest) }) it("should copy the directory successfully when dest is 'src-src/dest'", () => { const dest = path.join(TEST_DIR, 'src-src', 'dest') return testSuccess(src, dest) }) it("should copy the directory successfully when dest is 'srcsrc/dest'", () => { const dest = path.join(TEST_DIR, 'srcsrc', 'dest') return testSuccess(src, dest) }) it("should copy the directory successfully when dest is 'dest/src'", () => { const dest = path.join(TEST_DIR, 'dest', 'src') return testSuccess(src, dest) }) it('should copy the directory successfully when dest is very nested that all its parents need to be created', () => { const dest = path.join(TEST_DIR, 'dest', 'src', 'foo', 'bar', 'baz', 'qux', 'quux', 'waldo', 'grault', 'garply', 'fred', 'plugh', 'thud', 'some', 'highly', 'deeply', 'badly', 'nasty', 'crazy', 'mad', 'nested', 'dest') return testSuccess(src, dest) }) it("should error when dest is 'src/dest'", () => { const dest = path.join(TEST_DIR, 'src', 'dest') return testError(src, dest) }) it("should error when dest is 'src/src_dest'", () => { const dest = path.join(TEST_DIR, 'src', 'src_dest') return testError(src, dest) }) it("should error when dest is 'src/dest_src'", () => { const dest = path.join(TEST_DIR, 'src', 'dest_src') return testError(src, dest) }) it("should error when dest is 'src/dest/src'", () => { const dest = path.join(TEST_DIR, 'src', 'dest', 'src') return testError(src, dest) }) }) describe('>> when dest is a symlink', () => { it('should error when dest points exactly to src and dereference is true', () => { const destLink = path.join(TEST_DIR, 'dest-symlink') fs.symlinkSync(src, destLink, 'dir') const srclenBefore = klawSync(src).length assert(srclenBefore > 2) try { fs.copySync(src, destLink, { dereference: true }) } catch (err) { assert.strictEqual(err.message, 'Source and destination must not be the same.') } const srclenAfter = klawSync(src).length assert.strictEqual(srclenAfter, srclenBefore, 'src length should not change') const link = fs.readlinkSync(destLink) assert.strictEqual(link, src) }) it('should error when dest is a subdirectory of src (bind-mounted directory with subdirectory)', () => { const destLink = path.join(TEST_DIR, 'dest-symlink') fs.symlinkSync(src, destLink, 'dir') const srclenBefore = klawSync(src).length assert(srclenBefore > 2) const dest = path.join(destLink, 'dir1') assert(fs.existsSync(dest)) let errThrown = false try { fs.copySync(src, dest) } catch (err) { assert.strictEqual(err.message, `Cannot copy '${src}' to a subdirectory of itself, '${dest}'.`) errThrown = true } finally { assert(errThrown) const srclenAfter = klawSync(src).length assert.strictEqual(srclenAfter, srclenBefore, 'src length should not change') const link = fs.readlinkSync(destLink) assert.strictEqual(link, src) } }) it('should error when dest is a subdirectory of src (more than one level depth)', () => { const destLink = path.join(TEST_DIR, 'dest-symlink') fs.symlinkSync(src, destLink, 'dir') const srclenBefore = klawSync(src).length assert(srclenBefore > 2) const dest = path.join(destLink, 'dir1', 'dir2') assert(fs.existsSync(dest)) let errThrown = false try { fs.copySync(src, dest) } catch (err) { assert.strictEqual(err.message, `Cannot copy '${src}' to a subdirectory of itself, '${path.join(destLink, 'dir1')}'.`) errThrown = true } finally { assert(errThrown) const srclenAfter = klawSync(src).length assert.strictEqual(srclenAfter, srclenBefore, 'src length should not change') const link = fs.readlinkSync(destLink) assert.strictEqual(link, src) } }) it('should copy the directory successfully when src is a subdir of resolved dest path and dereferene is true', () => { const srcInDest = path.join(TEST_DIR, 'dest', 'some', 'nested', 'src') const destLink = path.join(TEST_DIR, 'dest-symlink') fs.copySync(src, srcInDest) // put some stuff in srcInDest const dest = path.join(TEST_DIR, 'dest') fs.symlinkSync(dest, destLink, 'dir') const srclen = klawSync(srcInDest).length const destlenBefore = klawSync(dest).length assert(srclen > 2) fs.copySync(srcInDest, destLink, { dereference: true }) const destlenAfter = klawSync(dest).length // assert dest length is oldlen + length of stuff copied from src assert.strictEqual(destlenAfter, destlenBefore + srclen, 'dest length should be equal to old length + copied legnth') FILES.forEach(f => assert(fs.existsSync(path.join(dest, f)), 'file copied')) const o0 = fs.readFileSync(path.join(dest, FILES[0]), 'utf8') const o1 = fs.readFileSync(path.join(dest, FILES[1]), 'utf8') const o2 = fs.readFileSync(path.join(dest, FILES[2]), 'utf8') const o3 = fs.readFileSync(path.join(dest, FILES[3]), 'utf8') assert.strictEqual(o0, dat0, 'files contents matched') assert.strictEqual(o1, dat1, 'files contents matched') assert.strictEqual(o2, dat2, 'files contents matched') assert.strictEqual(o3, dat3, 'files contents matched') }) }) }) describe('> when source is a symlink', () => { describe('>> when dest is a directory', () => { it('should error when resolved src path points to dest', () => { const srcLink = path.join(TEST_DIR, 'src-symlink') fs.symlinkSync(src, srcLink, 'dir') const dest = path.join(TEST_DIR, 'src') try { fs.copySync(srcLink, dest) } catch (err) { assert(err) } // assert source not affected const link = fs.readlinkSync(srcLink) assert.strictEqual(link, src) }) it('should error when dest is a subdir of resolved src path', () => { const srcLink = path.join(TEST_DIR, 'src-symlink') fs.symlinkSync(src, srcLink, 'dir') const dest = path.join(TEST_DIR, 'src', 'some', 'nested', 'dest') fs.mkdirsSync(dest) try { fs.copySync(srcLink, dest) } catch (err) { assert(err) } const link = fs.readlinkSync(srcLink) assert.strictEqual(link, src) }) it('should error when resolved src path is a subdir of dest', () => { const dest = path.join(TEST_DIR, 'dest') const resolvedSrcPath = path.join(dest, 'contains', 'src') const srcLink = path.join(TEST_DIR, 'src-symlink') fs.copySync(src, resolvedSrcPath) // make symlink that points to a subdir in dest fs.symlinkSync(resolvedSrcPath, srcLink, 'dir') try { fs.copySync(srcLink, dest) } catch (err) { assert(err) } }) it("should copy the directory successfully when dest is 'src_src/dest'", () => { const srcLink = path.join(TEST_DIR, 'src-symlink') fs.symlinkSync(src, srcLink, 'dir') const dest = path.join(TEST_DIR, 'src_src', 'dest') testSuccess(srcLink, dest) const link = fs.readlinkSync(dest) assert.strictEqual(link, src) }) it("should copy the directory successfully when dest is 'srcsrc/dest'", () => { const srcLink = path.join(TEST_DIR, 'src-symlink') fs.symlinkSync(src, srcLink, 'dir') const dest = path.join(TEST_DIR, 'srcsrc', 'dest') testSuccess(srcLink, dest) const link = fs.readlinkSync(dest) assert.strictEqual(link, src) }) }) describe('>> when dest is a symlink', () => { it('should error when resolved dest path is exactly the same as resolved src path and dereference is true', () => { const srcLink = path.join(TEST_DIR, 'src-symlink') fs.symlinkSync(src, srcLink, 'dir') const destLink = path.join(TEST_DIR, 'dest-symlink') fs.symlinkSync(src, destLink, 'dir') const srclenBefore = klawSync(srcLink).length const destlenBefore = klawSync(destLink).length assert(srclenBefore > 2) assert(destlenBefore > 2) try { fs.copySync(srcLink, destLink, { dereference: true }) } catch (err) { assert.strictEqual(err.message, 'Source and destination must not be the same.') } finally { const srclenAfter = klawSync(srcLink).length assert.strictEqual(srclenAfter, srclenBefore, 'src length should not change') const destlenAfter = klawSync(destLink).length assert.strictEqual(destlenAfter, destlenBefore, 'dest length should not change') const srcln = fs.readlinkSync(srcLink) assert.strictEqual(srcln, src) const destln = fs.readlinkSync(destLink) assert.strictEqual(destln, src) } }) it('should error when resolved dest path is a subdir of resolved src path', () => { const srcLink = path.join(TEST_DIR, 'src-symlink') fs.symlinkSync(src, srcLink, 'dir') const destLink = path.join(TEST_DIR, 'dest-symlink') const resolvedDestPath = path.join(TEST_DIR, 'src', 'some', 'nested', 'dest') fs.ensureFileSync(path.join(resolvedDestPath, 'subdir', 'somefile.txt')) fs.symlinkSync(resolvedDestPath, destLink, 'dir') try { fs.copySync(srcLink, destLink) } catch (err) { assert.strictEqual(err.message, `Cannot copy '${src}' to a subdirectory of itself, '${resolvedDestPath}'.`) } finally { const destln = fs.readlinkSync(destLink) assert.strictEqual(destln, resolvedDestPath) } }) it('should error when resolved src path is a subdir of resolved dest path', () => { const srcInDest = path.join(TEST_DIR, 'dest', 'some', 'nested', 'src') const srcLink = path.join(TEST_DIR, 'src-symlink') const destLink = path.join(TEST_DIR, 'dest-symlink') const dest = path.join(TEST_DIR, 'dest') fs.ensureDirSync(srcInDest) fs.ensureSymlinkSync(srcInDest, srcLink, 'dir') fs.ensureSymlinkSync(dest, destLink, 'dir') try { fs.copySync(srcLink, destLink) } catch (err) { assert.strictEqual(err.message, `Cannot overwrite '${dest}' with '${srcInDest}'.`) } finally { const destln = fs.readlinkSync(destLink) assert.strictEqual(destln, dest) } }) }) }) }) function testSuccess (src, dest) { const srclen = klawSync(src).length assert(srclen > 2) fs.copySync(src, dest) FILES.forEach(f => assert(fs.existsSync(path.join(dest, f)), 'file copied')) const o0 = fs.readFileSync(path.join(dest, FILES[0]), 'utf8') const o1 = fs.readFileSync(path.join(dest, FILES[1]), 'utf8') const o2 = fs.readFileSync(path.join(dest, FILES[2]), 'utf8') const o3 = fs.readFileSync(path.join(dest, FILES[3]), 'utf8') assert.strictEqual(o0, dat0, 'file contents matched') assert.strictEqual(o1, dat1, 'file contents matched') assert.strictEqual(o2, dat2, 'file contents matched') assert.strictEqual(o3, dat3, 'file contents matched') } function testError (src, dest) { try { fs.copySync(src, dest) } catch (err) { assert.strictEqual(err.message, `Cannot copy '${src}' to a subdirectory of itself, '${dest}'.`) } } ================================================ FILE: lib/copy/__tests__/copy-sync-readonly-dir.test.js ================================================ 'use strict' // relevant: https://github.com/jprichardson/node-fs-extra/issues/599 const os = require('os') const fs = require('../../') const path = require('path') const assert = require('assert') const klawSync = require('klaw-sync') /* global afterEach, beforeEach, describe, it */ let TEST_DIR = '' const FILES = [ path.join('dir1', 'file1.txt'), path.join('dir1', 'dir2', 'file2.txt'), path.join('dir1', 'dir2', 'dir3', 'file3.txt') ] describe('+ copySync() - copy a readonly directory with content', () => { beforeEach(done => { TEST_DIR = path.join(os.tmpdir(), 'test', 'fs-extra', 'copy-readonly-dir') fs.emptyDir(TEST_DIR, done) }) afterEach(done => { klawSync(TEST_DIR).forEach(data => fs.chmodSync(data.path, 0o777)) fs.remove(TEST_DIR, done) }) describe('> when src is readonly directory with content', () => { it('should copy successfully', () => { FILES.forEach(file => { fs.outputFileSync(path.join(TEST_DIR, file), file) }) const sourceDir = path.join(TEST_DIR, 'dir1') const sourceHierarchy = klawSync(sourceDir) sourceHierarchy.forEach(source => fs.chmodSync(source.path, source.stats.isDirectory() ? 0o555 : 0o444)) const targetDir = path.join(TEST_DIR, 'target') fs.copySync(sourceDir, targetDir) // Make sure copy was made and mode was preserved assert(fs.existsSync(targetDir)) const targetHierarchy = klawSync(targetDir) assert(targetHierarchy.length === sourceHierarchy.length) targetHierarchy.forEach(target => assert(target.stats.mode === target.stats.isDirectory() ? 0o555 : 0o444)) }) }) }) ================================================ FILE: lib/copy/__tests__/copy-sync-symlink-same-target.test.js ================================================ 'use strict' const os = require('os') const fs = require('../..') const path = require('path') const assert = require('assert') const copySync = require('../copy-sync') /* global afterEach, beforeEach, describe, it */ describe('copy-sync / symlink same target', () => { const TEST_DIR = path.join(os.tmpdir(), 'fs-extra', 'copy-sync-symlink-same-target') beforeEach(done => { fs.emptyDir(TEST_DIR, done) }) afterEach(done => { fs.remove(TEST_DIR, done) }) describe('> when copying directory containing symlink', () => { it('should copy symlink when dest has no existing symlink', () => { const target = path.join(TEST_DIR, 'target') const src = path.join(TEST_DIR, 'src') const dest = path.join(TEST_DIR, 'dest') // Setup fs.mkdirpSync(target) fs.writeFileSync(path.join(target, 'file.txt'), 'content') fs.mkdirpSync(src) fs.symlinkSync(target, path.join(src, 'link'), 'dir') // Copy assert.doesNotThrow(() => { copySync(src, dest) }) // Verify symlink was copied const destLink = path.join(dest, 'link') assert.ok(fs.lstatSync(destLink).isSymbolicLink()) assert.strictEqual(fs.readlinkSync(destLink), target) }) // Also tests issue #1027 it('should overwrite symlink when dest has existing symlink pointing to SAME target', () => { const target = path.join(TEST_DIR, 'target') const src = path.join(TEST_DIR, 'src') const dest = path.join(TEST_DIR, 'dest') // Setup fs.mkdirpSync(target) fs.writeFileSync(path.join(target, 'file.txt'), 'content') fs.mkdirpSync(src) fs.mkdirpSync(dest) // Create symlinks pointing to the same target fs.symlinkSync(target, path.join(src, 'link'), 'dir') fs.symlinkSync(target, path.join(dest, 'link'), 'dir') // Copy should work - two different symlinks pointing to same target are NOT the same file assert.doesNotThrow(() => { copySync(src, dest) }) // Verify symlink was copied/overwritten const destLink = path.join(dest, 'link') assert.ok(fs.lstatSync(destLink).isSymbolicLink()) assert.strictEqual(fs.readlinkSync(destLink), target) }) it('should overwrite symlink when dest has existing symlink pointing to DIFFERENT target', () => { const target1 = path.join(TEST_DIR, 'target1') const target2 = path.join(TEST_DIR, 'target2') const src = path.join(TEST_DIR, 'src') const dest = path.join(TEST_DIR, 'dest') // Setup fs.mkdirpSync(target1) fs.mkdirpSync(target2) fs.writeFileSync(path.join(target1, 'file.txt'), 'content1') fs.writeFileSync(path.join(target2, 'file.txt'), 'content2') fs.mkdirpSync(src) fs.mkdirpSync(dest) // Create symlinks pointing to different targets fs.symlinkSync(target1, path.join(src, 'link'), 'dir') fs.symlinkSync(target2, path.join(dest, 'link'), 'dir') // Copy should work assert.doesNotThrow(() => { copySync(src, dest) }) // Verify symlink was copied/overwritten to point to target1 const destLink = path.join(dest, 'link') assert.ok(fs.lstatSync(destLink).isSymbolicLink()) assert.strictEqual(fs.readlinkSync(destLink), target1) }) }) describe('> when copying file symlinks', () => { it('should overwrite file symlink when dest has existing symlink pointing to SAME target', () => { const target = path.join(TEST_DIR, 'target.txt') const src = path.join(TEST_DIR, 'src') const dest = path.join(TEST_DIR, 'dest') // Setup fs.writeFileSync(target, 'content') fs.mkdirpSync(src) fs.mkdirpSync(dest) // Create file symlinks pointing to the same target fs.symlinkSync(target, path.join(src, 'link'), 'file') fs.symlinkSync(target, path.join(dest, 'link'), 'file') // Copy should work assert.doesNotThrow(() => { copySync(src, dest) }) // Verify symlink was copied/overwritten const destLink = path.join(dest, 'link') assert.ok(fs.lstatSync(destLink).isSymbolicLink()) assert.strictEqual(fs.readlinkSync(destLink), target) }) it('should overwrite file symlink when dest has existing symlink pointing to DIFFERENT target', () => { const target1 = path.join(TEST_DIR, 'target1.txt') const target2 = path.join(TEST_DIR, 'target2.txt') const src = path.join(TEST_DIR, 'src') const dest = path.join(TEST_DIR, 'dest') // Setup fs.writeFileSync(target1, 'content1') fs.writeFileSync(target2, 'content2') fs.mkdirpSync(src) fs.mkdirpSync(dest) // Create file symlinks pointing to different targets fs.symlinkSync(target1, path.join(src, 'link'), 'file') fs.symlinkSync(target2, path.join(dest, 'link'), 'file') // Copy should work assert.doesNotThrow(() => { copySync(src, dest) }) // Verify symlink was copied/overwritten to point to target1 const destLink = path.join(dest, 'link') assert.ok(fs.lstatSync(destLink).isSymbolicLink()) assert.strictEqual(fs.readlinkSync(destLink), target1) }) }) describe('> when copying symlink directly to another symlink (issue #1019)', () => { it('should copy symlink to another symlink pointing to same target', () => { const target = path.join(TEST_DIR, 'target.txt') const srcLink = path.join(TEST_DIR, 'srcLink') const destLink = path.join(TEST_DIR, 'destLink') // Setup - two different symlinks pointing to the same file fs.writeFileSync(target, 'content') fs.symlinkSync(target, srcLink, 'file') fs.symlinkSync(target, destLink, 'file') // Copy should work - these are different symlinks even though they point to the same target assert.doesNotThrow(() => { copySync(srcLink, destLink) }) assert.ok(fs.lstatSync(destLink).isSymbolicLink()) assert.strictEqual(fs.readlinkSync(destLink), target) }) }) describe('> edge cases', () => { it('should still prevent copying a symlink to itself', () => { const target = path.join(TEST_DIR, 'target') const link = path.join(TEST_DIR, 'link') // Setup fs.mkdirpSync(target) fs.symlinkSync(target, link, 'dir') // Copying a symlink to itself should fail assert.throws(() => { copySync(link, link) }, /Source and destination must not be the same/) }) it('should allow copying symlink to subdirectory of its target (symlink copy, not recursive)', () => { // When copying a symlink (not dereferencing), we just copy the link itself // This should be allowed because we're not recursively copying the target's contents const target = path.join(TEST_DIR, 'target') const src = path.join(TEST_DIR, 'src') // Setup fs.mkdirpSync(target) fs.mkdirpSync(path.join(target, 'subdir')) fs.mkdirpSync(src) fs.symlinkSync(target, path.join(src, 'link'), 'dir') // Dest is inside src's resolved target const dest = path.join(target, 'subdir', 'dest') // This should work - we're just copying the symlink, not following it assert.doesNotThrow(() => { copySync(src, dest) }) // Verify symlink was copied const destLink = path.join(dest, 'link') assert.ok(fs.lstatSync(destLink).isSymbolicLink()) assert.strictEqual(fs.readlinkSync(destLink), target) }) }) }) ================================================ FILE: lib/copy/__tests__/copy-sync-symlink.test.js ================================================ 'use strict' const os = require('os') const fs = require('../..') const path = require('path') const assert = require('assert') const copySync = require('../copy-sync') /* global afterEach, beforeEach, describe, it */ describe('copy-sync / symlink', () => { const TEST_DIR = path.join(os.tmpdir(), 'fs-extra', 'copy-sync-symlinks') const src = path.join(TEST_DIR, 'src') const out = path.join(TEST_DIR, 'out') beforeEach(done => { fs.emptyDir(TEST_DIR, err => { assert.ifError(err) createFixtures(src, done) }) }) afterEach(done => { fs.remove(TEST_DIR, done) }) it('copies symlinks by default', () => { assert.doesNotThrow(() => { copySync(src, out) }) assert.strictEqual(fs.readlinkSync(path.join(out, 'file-symlink')), path.join(src, 'foo')) assert.strictEqual(fs.readlinkSync(path.join(out, 'dir-symlink')), path.join(src, 'dir')) }) it('copies file contents when dereference=true', () => { try { copySync(src, out, { dereference: true }) } catch (err) { assert.ifError(err) } const fileSymlinkPath = path.join(out, 'file-symlink') assert.ok(fs.lstatSync(fileSymlinkPath).isFile()) assert.strictEqual(fs.readFileSync(fileSymlinkPath, 'utf8'), 'foo contents') const dirSymlinkPath = path.join(out, 'dir-symlink') assert.ok(fs.lstatSync(dirSymlinkPath).isDirectory()) assert.deepStrictEqual(fs.readdirSync(dirSymlinkPath), ['bar']) }) }) function createFixtures (srcDir, callback) { fs.mkdir(srcDir, err => { if (err) return callback(err) // note: third parameter in symlinkSync is type e.g. 'file' or 'dir' // https://nodejs.org/api/fs.html#fs_fs_symlink_srcpath_dstpath_type_callback try { const fooFile = path.join(srcDir, 'foo') const fooFileLink = path.join(srcDir, 'file-symlink') fs.writeFileSync(fooFile, 'foo contents') fs.symlinkSync(fooFile, fooFileLink, 'file') const dir = path.join(srcDir, 'dir') const dirFile = path.join(dir, 'bar') const dirLink = path.join(srcDir, 'dir-symlink') fs.mkdirSync(dir) fs.writeFileSync(dirFile, 'bar contents') fs.symlinkSync(dir, dirLink, 'dir') } catch (err) { callback(err) } callback() }) } ================================================ FILE: lib/copy/__tests__/copy.test.js ================================================ 'use strict' const fs = require('fs') const os = require('os') const fse = require('../../') const path = require('path') const assert = require('assert') const crypto = require('crypto') /* global afterEach, beforeEach, describe, it */ const SIZE = 16 * 64 * 1024 + 7 let TEST_DIR = '' describe('fs-extra', () => { beforeEach(done => { TEST_DIR = path.join(os.tmpdir(), 'fs-extra', 'copy') fse.emptyDir(TEST_DIR, done) }) afterEach(done => fse.remove(TEST_DIR, done)) describe('+ copy()', () => { it('should return an error if src and dest are the same', done => { const fileSrc = path.join(TEST_DIR, 'TEST_fs-extra_copy') const fileDest = path.join(TEST_DIR, 'TEST_fs-extra_copy') fse.ensureFileSync(fileSrc) fse.copy(fileSrc, fileDest, err => { assert.strictEqual(err.message, 'Source and destination must not be the same.') done() }) }) it('should error when overwrite=false and file exists', done => { const src = path.join(TEST_DIR, 'src.txt') const dest = path.join(TEST_DIR, 'dest.txt') fse.ensureFileSync(src) fse.ensureFileSync(dest) fse.copy(src, dest, { overwrite: false, errorOnExist: true }, err => { assert(err) done() }) }) it('should error when overwrite=false and file exists in a dir', done => { const src = path.join(TEST_DIR, 'src', 'sfile.txt') const dest = path.join(TEST_DIR, 'dest', 'dfile.txt') fse.ensureFileSync(src) fse.ensureFileSync(dest) fse.copy(src, dest, { overwrite: false, errorOnExist: true }, err => { assert(err) done() }) }) describe('> when src is a file', () => { it('should copy the file asynchronously', done => { const fileSrc = path.join(TEST_DIR, 'TEST_fs-extra_src') const fileDest = path.join(TEST_DIR, 'TEST_fs-extra_copy') fs.writeFileSync(fileSrc, crypto.randomBytes(SIZE)) const srcMd5 = crypto.createHash('md5').update(fs.readFileSync(fileSrc)).digest('hex') let destMd5 = '' fse.copy(fileSrc, fileDest, err => { assert(!err) destMd5 = crypto.createHash('md5').update(fs.readFileSync(fileDest)).digest('hex') assert.strictEqual(srcMd5, destMd5) done() }) }) it('should work with promises', () => { const fileSrc = path.join(TEST_DIR, 'TEST_fs-extra_src') const fileDest = path.join(TEST_DIR, 'TEST_fs-extra_copy') fs.writeFileSync(fileSrc, crypto.randomBytes(SIZE)) const srcMd5 = crypto.createHash('md5').update(fs.readFileSync(fileSrc)).digest('hex') let destMd5 = '' return fse.copy(fileSrc, fileDest).then(() => { destMd5 = crypto.createHash('md5').update(fs.readFileSync(fileDest)).digest('hex') assert.strictEqual(srcMd5, destMd5) }) }) it('should return an error if src file does not exist', done => { const fileSrc = 'we-simply-assume-this-file-does-not-exist.bin' const fileDest = path.join(TEST_DIR, 'TEST_fs-extra_copy') fse.copy(fileSrc, fileDest, err => { assert(err) done() }) }) it('should copy to a destination file with two \'$\' characters in name (eg: TEST_fs-extra_$$_copy)', done => { const fileSrc = path.join(TEST_DIR, 'TEST_fs-extra_src') const fileDest = path.join(TEST_DIR, 'TEST_fs-extra_$$_copy') fs.writeFileSync(fileSrc, '') fse.copy(fileSrc, fileDest, err => { assert(!err) fs.statSync(fileDest) done() }) }) describe('> when the destination dir does not exist', () => { it('should create the destination directory and copy the file', done => { const src = path.join(TEST_DIR, 'file.txt') const dest = path.join(TEST_DIR, 'this/path/does/not/exist/copied.txt') const data = 'did it copy?\n' fs.writeFileSync(src, data, 'utf8') fse.copy(src, dest, err => { const data2 = fs.readFileSync(dest, 'utf8') assert.strictEqual(data, data2) done(err) }) }) }) describe('> when dest exists and is a directory', () => { it('should return an error', done => { const src = path.join(TEST_DIR, 'file.txt') const dest = path.join(TEST_DIR, 'dir') fse.ensureFileSync(src) fse.ensureDirSync(dest) fse.copy(src, dest, err => { assert.strictEqual(err.message, `Cannot overwrite directory '${dest}' with non-directory '${src}'.`) done() }) }) }) }) describe('> when src is a directory', () => { describe('> when src directory does not exist', () => { it('should return an error', done => { const ts = path.join(TEST_DIR, 'this_dir_does_not_exist') const td = path.join(TEST_DIR, 'this_dir_really_does_not_matter') fse.copy(ts, td, err => { assert(err) done() }) }) }) describe('> when dest exists and is a file', () => { it('should return an error', done => { const src = path.join(TEST_DIR, 'src') const dest = path.join(TEST_DIR, 'file.txt') fs.mkdirSync(src) fse.ensureFileSync(dest) fse.copy(src, dest, err => { assert.strictEqual(err.message, `Cannot overwrite non-directory '${dest}' with directory '${src}'.`) done() }) }) }) it('should preserve symbolic links', done => { const src = path.join(TEST_DIR, 'src') const dest = path.join(TEST_DIR, 'dest') const srcTarget = path.join(TEST_DIR, 'destination') fse.mkdirSync(src) fse.mkdirSync(srcTarget) // symlink type is only used for Windows and the default is 'file'. // https://nodejs.org/api/fs.html#fs_fs_symlink_target_path_type_callback fse.symlinkSync(srcTarget, path.join(src, 'symlink'), 'dir') fse.copy(src, dest, err => { assert.ifError(err) const link = fs.readlinkSync(path.join(dest, 'symlink')) assert.strictEqual(link, srcTarget) done() }) }) it('should copy the directory asynchronously', done => { const FILES = 2 const src = path.join(TEST_DIR, 'src') const dest = path.join(TEST_DIR, 'dest') fse.mkdirs(src, err => { assert(!err) for (let i = 0; i < FILES; ++i) { fs.writeFileSync(path.join(src, i.toString()), crypto.randomBytes(SIZE)) } const subdir = path.join(src, 'subdir') fse.mkdirs(subdir, err => { assert(!err) for (let i = 0; i < FILES; ++i) { fs.writeFileSync(path.join(subdir, i.toString()), crypto.randomBytes(SIZE)) } fse.copy(src, dest, err => { assert.ifError(err) assert(fs.existsSync(dest)) for (let i = 0; i < FILES; ++i) { assert(fs.existsSync(path.join(dest, i.toString()))) } const destSub = path.join(dest, 'subdir') for (let j = 0; j < FILES; ++j) { assert(fs.existsSync(path.join(destSub, j.toString()))) } done() }) }) }) }) describe('> when the destination dir does not exist', () => { it('should create the destination directory and copy the file', done => { const src = path.join(TEST_DIR, 'data/') fse.mkdirsSync(src) const d1 = 'file1' const d2 = 'file2' fs.writeFileSync(path.join(src, 'f1.txt'), d1) fs.writeFileSync(path.join(src, 'f2.txt'), d2) const dest = path.join(TEST_DIR, 'this/path/does/not/exist/outputDir') fse.copy(src, dest, err => { const o1 = fs.readFileSync(path.join(dest, 'f1.txt'), 'utf8') const o2 = fs.readFileSync(path.join(dest, 'f2.txt'), 'utf8') assert.strictEqual(d1, o1) assert.strictEqual(d2, o2) done(err) }) }) }) describe('> when src dir does not exist', () => { it('should return an error', done => { fse.copy('/does/not/exist', '/something/else', err => { assert(err instanceof Error) done() }) }) }) }) describe('> when filter is used', () => { it('should do nothing if filter fails', done => { const srcDir = path.join(TEST_DIR, 'src') const srcFile = path.join(srcDir, 'srcfile.css') fse.outputFileSync(srcFile, 'src contents') const destDir = path.join(TEST_DIR, 'dest') const destFile = path.join(destDir, 'destfile.css') const filter = s => path.extname(s) !== '.css' && !fs.statSync(s).isDirectory() fse.copy(srcFile, destFile, filter, err => { assert.ifError(err) assert(!fs.existsSync(destDir)) done() }) }) it('should only copy files allowed by filter fn', done => { const srcFile1 = path.join(TEST_DIR, '1.css') fs.writeFileSync(srcFile1, '') const destFile1 = path.join(TEST_DIR, 'dest1.css') const filter = s => s.split('.').pop() !== 'css' fse.copy(srcFile1, destFile1, filter, err => { assert(!err) assert(!fs.existsSync(destFile1)) done() }) }) it('should not call filter fn more than needed', done => { const src = path.join(TEST_DIR, 'foo') fs.writeFileSync(src, '') const dest = path.join(TEST_DIR, 'bar') let filterCallCount = 0 const filter = () => { filterCallCount++ return true } fse.copy(src, dest, filter, err => { assert(!err) assert.strictEqual(filterCallCount, 1) assert(fs.existsSync(dest)) done() }) }) it('accepts options object in place of filter', done => { const srcFile1 = path.join(TEST_DIR, '1.jade') fs.writeFileSync(srcFile1, '') const destFile1 = path.join(TEST_DIR, 'dest1.jade') const options = { filter: s => /.html$|.css$/i.test(s) } fse.copy(srcFile1, destFile1, options, (err) => { assert(!err) assert(!fs.existsSync(destFile1)) done() }) }) it('allows filter fn to return a promise', done => { const srcFile1 = path.join(TEST_DIR, '1.css') fs.writeFileSync(srcFile1, '') const destFile1 = path.join(TEST_DIR, 'dest1.css') const filter = s => Promise.resolve(s.split('.').pop() !== 'css') fse.copy(srcFile1, destFile1, filter, err => { assert(!err) assert(!fs.existsSync(destFile1)) done() }) }) it('should apply filter recursively', done => { const FILES = 2 // Don't match anything that ends with a digit higher than 0: const filter = s => /(0|\D)$/i.test(s) const src = path.join(TEST_DIR, 'src') fse.mkdirsSync(src) for (let i = 0; i < FILES; ++i) { fs.writeFileSync(path.join(src, i.toString()), crypto.randomBytes(SIZE)) } const subdir = path.join(src, 'subdir') fse.mkdirsSync(subdir) for (let i = 0; i < FILES; ++i) { fs.writeFileSync(path.join(subdir, i.toString()), crypto.randomBytes(SIZE)) } const dest = path.join(TEST_DIR, 'dest') fse.copy(src, dest, filter, err => { assert(!err) assert(fs.existsSync(dest)) assert(FILES > 1) for (let i = 0; i < FILES; ++i) { if (i === 0) { assert(fs.existsSync(path.join(dest, i.toString()))) } else { assert(!fs.existsSync(path.join(dest, i.toString()))) } } const destSub = path.join(dest, 'subdir') for (let j = 0; j < FILES; ++j) { if (j === 0) { assert(fs.existsSync(path.join(destSub, j.toString()))) } else { assert(!fs.existsSync(path.join(destSub, j.toString()))) } } done() }) }) it('should apply filter to directory names', done => { const IGNORE = 'ignore' const filter = p => !~p.indexOf(IGNORE) const src = path.join(TEST_DIR, 'src') fse.mkdirsSync(src) const ignoreDir = path.join(src, IGNORE) fse.mkdirsSync(ignoreDir) fse.writeFileSync(path.join(ignoreDir, 'file'), crypto.randomBytes(SIZE)) const dest = path.join(TEST_DIR, 'dest') fse.copy(src, dest, filter, err => { assert.ifError(err) assert(!fs.existsSync(path.join(dest, IGNORE)), 'directory was not ignored') assert(!fs.existsSync(path.join(dest, IGNORE, 'file')), 'file was not ignored') done() }) }) it('should apply filter when it is applied only to dest', done => { const timeCond = new Date().getTime() const filter = (s, d) => fs.statSync(d).mtime.getTime() < timeCond const src = path.join(TEST_DIR, 'src') fse.mkdirsSync(src) const subdir = path.join(src, 'subdir') fse.mkdirsSync(subdir) const dest = path.join(TEST_DIR, 'dest') setTimeout(() => { fse.mkdirsSync(dest) fse.copy(src, dest, filter, err => { assert(!err) assert(!fs.existsSync(path.join(dest, 'subdir'))) done() }) }, 1000) }) it('should apply filter when it is applied to both src and dest', done => { const timeCond = new Date().getTime() const filter = (s, d) => s.split('.').pop() !== 'css' && fs.statSync(path.dirname(d)).mtime.getTime() > timeCond const dest = path.join(TEST_DIR, 'dest') setTimeout(() => { fse.mkdirsSync(dest) const srcFile1 = path.join(TEST_DIR, '1.html') const srcFile2 = path.join(TEST_DIR, '2.css') const srcFile3 = path.join(TEST_DIR, '3.jade') fse.writeFileSync(srcFile1, '') fse.writeFileSync(srcFile2, '') fse.writeFileSync(srcFile3, '') const destFile1 = path.join(dest, 'dest1.html') const destFile2 = path.join(dest, 'dest2.css') const destFile3 = path.join(dest, 'dest3.jade') fse.copy(srcFile1, destFile1, filter, err => { assert(!err) assert(fs.existsSync(destFile1)) fse.copy(srcFile2, destFile2, filter, err => { assert(!err) assert(!fs.existsSync(destFile2)) fse.copy(srcFile3, destFile3, filter, err => { assert(!err) assert(fs.existsSync(destFile3)) done() }) }) }) }, 1000) }) }) }) }) ================================================ FILE: lib/copy/__tests__/ncp/README.md ================================================ These tests came from: https://github.com/AvianFlu/ncp/tree/v1.0.1/test ================================================ FILE: lib/copy/__tests__/ncp/broken-symlink.test.js ================================================ 'use strict' const fs = require('fs') const os = require('os') const fse = require('../../..') const { copy: ncp } = require('../../') const path = require('path') const assert = require('assert') /* global afterEach, beforeEach, describe, it */ describe('ncp broken symlink', () => { const TEST_DIR = path.join(os.tmpdir(), 'fs-extra', 'ncp-broken-symlinks') const src = path.join(TEST_DIR, 'src') const out = path.join(TEST_DIR, 'out') beforeEach(done => { fse.emptyDir(TEST_DIR, err => { assert.ifError(err) createFixtures(src, done) }) }) afterEach(done => fse.remove(TEST_DIR, done)) it('should not error if symlink is broken', done => { ncp(src, out, err => { assert.strictEqual(err, null) done() }) }) it('should return an error if symlink is broken and dereference=true', done => { ncp(src, out, { dereference: true }, err => { assert.strictEqual(err.code, 'ENOENT') done() }) }) }) function createFixtures (srcDir, callback) { fs.mkdir(srcDir, err => { let brokenFile let brokenFileLink if (err) return callback(err) try { brokenFile = path.join(srcDir, 'does-not-exist') brokenFileLink = path.join(srcDir, 'broken-symlink') fs.writeFileSync(brokenFile, 'does not matter') fs.symlinkSync(brokenFile, brokenFileLink, 'file') } catch (err) { callback(err) } // break the symlink now fse.remove(brokenFile, callback) }) } ================================================ FILE: lib/copy/__tests__/ncp/fixtures/modified-files/out/a ================================================ test2 ================================================ FILE: lib/copy/__tests__/ncp/fixtures/modified-files/src/a ================================================ test3 ================================================ FILE: lib/copy/__tests__/ncp/fixtures/regular-fixtures/out/a ================================================ Hello world ================================================ FILE: lib/copy/__tests__/ncp/fixtures/regular-fixtures/out/b ================================================ Hello ncp ================================================ FILE: lib/copy/__tests__/ncp/fixtures/regular-fixtures/out/c ================================================ ================================================ FILE: lib/copy/__tests__/ncp/fixtures/regular-fixtures/out/d ================================================ ================================================ FILE: lib/copy/__tests__/ncp/fixtures/regular-fixtures/out/e ================================================ ================================================ FILE: lib/copy/__tests__/ncp/fixtures/regular-fixtures/out/f ================================================ ================================================ FILE: lib/copy/__tests__/ncp/fixtures/regular-fixtures/out/sub/a ================================================ Hello nodejitsu ================================================ FILE: lib/copy/__tests__/ncp/fixtures/regular-fixtures/out/sub/b ================================================ ================================================ FILE: lib/copy/__tests__/ncp/fixtures/regular-fixtures/src/a ================================================ Hello world ================================================ FILE: lib/copy/__tests__/ncp/fixtures/regular-fixtures/src/b ================================================ Hello ncp ================================================ FILE: lib/copy/__tests__/ncp/fixtures/regular-fixtures/src/c ================================================ ================================================ FILE: lib/copy/__tests__/ncp/fixtures/regular-fixtures/src/d ================================================ ================================================ FILE: lib/copy/__tests__/ncp/fixtures/regular-fixtures/src/e ================================================ ================================================ FILE: lib/copy/__tests__/ncp/fixtures/regular-fixtures/src/f ================================================ ================================================ FILE: lib/copy/__tests__/ncp/fixtures/regular-fixtures/src/sub/a ================================================ Hello nodejitsu ================================================ FILE: lib/copy/__tests__/ncp/fixtures/regular-fixtures/src/sub/b ================================================ ================================================ FILE: lib/copy/__tests__/ncp/ncp-error-perm.test.js ================================================ 'use strict' // file in reference: https://github.com/jprichardson/node-fs-extra/issues/56 const fs = require('fs') const os = require('os') const fse = require('../../..') const { copy: ncp } = require('../../') const path = require('path') const assert = require('assert') /* global afterEach, beforeEach, describe, it */ // skip test for windows // eslint-disable globalReturn */ // if (os.platform().indexOf('win') === 0) return // eslint-enable globalReturn */ describe('ncp / error / dest-permission', () => { const TEST_DIR = path.join(os.tmpdir(), 'fs-extra', 'ncp-error-dest-perm') const src = path.join(TEST_DIR, 'src') const dest = path.join(TEST_DIR, 'dest') // when we are root, then we will be able to create the subdirectory even if // we don't have the permissions to do so, so no point in running this test if (os.platform().indexOf('win') === 0 || os.userInfo().uid === 0) return beforeEach(done => { fse.emptyDir(TEST_DIR, err => { assert.ifError(err) done() }) }) afterEach(done => fse.remove(TEST_DIR, done)) it('should return an error', done => { const someFile = path.join(src, 'some-file') fse.outputFileSync(someFile, 'hello') fse.mkdirsSync(dest) fs.chmodSync(dest, 0o444) const subdest = path.join(dest, 'another-dir') ncp(src, subdest, err => { assert(err) assert.strictEqual(err.code, 'EACCES') done() }) }) }) ================================================ FILE: lib/copy/__tests__/ncp/ncp.test.js ================================================ 'use strict' const fs = require('fs') const { copy: ncp } = require('../../') const path = require('path') const rimraf = require('rimraf') const assert = require('assert') const readDirFiles = require('read-dir-files').read // temporary, will remove /* eslint-env mocha */ const fixturesDir = path.join(__dirname, 'fixtures') describe('ncp', () => { describe('regular files and directories', () => { const fixtures = path.join(fixturesDir, 'regular-fixtures') const src = path.join(fixtures, 'src') const out = path.join(fixtures, 'out') before(cb => rimraf(out, () => ncp(src, out, cb))) describe('when copying a directory of files', () => { it('files are copied correctly', cb => { readDirFiles(src, 'utf8', (srcErr, srcFiles) => { readDirFiles(out, 'utf8', (outErr, outFiles) => { assert.ifError(srcErr) assert.deepStrictEqual(srcFiles, outFiles) cb() }) }) }) }) describe('when copying files using filter', () => { before(cb => { const filter = name => name.slice(-1) !== 'a' rimraf(out, () => ncp(src, out, { filter }, cb)) }) it('files are copied correctly', cb => { readDirFiles(src, 'utf8', (srcErr, srcFiles) => { function filter (files) { for (const fileName in files) { const curFile = files[fileName] if (curFile instanceof Object) { filter(curFile) } else if (fileName.slice(-1) === 'a') { delete files[fileName] } } } filter(srcFiles) readDirFiles(out, 'utf8', (outErr, outFiles) => { assert.ifError(outErr) assert.deepStrictEqual(srcFiles, outFiles) cb() }) }) }) }) describe('when using overwrite=true', () => { before(function () { this.originalCreateReadStream = fs.createReadStream }) after(function () { fs.createReadStream = this.originalCreateReadStream }) it('the copy is complete after callback', done => { ncp(src, out, { overwrite: true }, err => { fs.createReadStream = () => done(new Error('createReadStream after callback')) assert.ifError(err) process.nextTick(done) }) }) }) describe('when using overwrite=false', () => { beforeEach(done => rimraf(out, done)) it('works', cb => { ncp(src, out, { overwrite: false }, err => { assert.ifError(err) cb() }) }) it('should not error if files exist', cb => { ncp(src, out, () => { ncp(src, out, { overwrite: false }, err => { assert.ifError(err) cb() }) }) }) it('should error if errorOnExist and file exists', cb => { ncp(src, out, () => { ncp(src, out, { overwrite: false, errorOnExist: true }, err => { assert(err) cb() }) }) }) }) describe('clobber', () => { beforeEach(done => rimraf(out, done)) it('is an alias for overwrite', cb => { ncp(src, out, () => { ncp(src, out, { clobber: false, errorOnExist: true }, err => { assert(err) cb() }) }) }) }) describe('when using transform', () => { it('file descriptors are passed correctly', cb => { ncp(src, out, { transform: (read, write, file) => { assert.notStrictEqual(file.name, undefined) assert.strictEqual(typeof file.mode, 'number') read.pipe(write) } }, cb) }) }) }) // see https://github.com/AvianFlu/ncp/issues/71 describe('Issue 71: Odd Async Behaviors', () => { const fixtures = path.join(__dirname, 'fixtures', 'regular-fixtures') const src = path.join(fixtures, 'src') const out = path.join(fixtures, 'out') let totalCallbacks = 0 function copyAssertAndCount (callback) { // rimraf(out, function() { ncp(src, out, err => { assert(!err) totalCallbacks += 1 readDirFiles(src, 'utf8', (srcErr, srcFiles) => { readDirFiles(out, 'utf8', (outErr, outFiles) => { assert.ifError(srcErr) assert.deepStrictEqual(srcFiles, outFiles) callback() }) }) }) // }) } describe('when copying a directory of files without cleaning the destination', () => { it('callback fires once per run and directories are equal', done => { const expected = 10 let count = 10 function next () { if (count > 0) { setTimeout(() => { copyAssertAndCount(() => { count -= 1 next() }) }, 100) } else { // console.log('Total callback count is', totalCallbacks) assert.strictEqual(totalCallbacks, expected) done() } } next() }) }) }) }) ================================================ FILE: lib/copy/__tests__/ncp/symlink.test.js ================================================ 'use strict' const fs = require('fs') const os = require('os') const fse = require('../../..') const { copy: ncp } = require('../../') const path = require('path') const assert = require('assert') /* global afterEach, beforeEach, describe, it */ describe('ncp / symlink', () => { const TEST_DIR = path.join(os.tmpdir(), 'fs-extra', 'ncp-symlinks') const src = path.join(TEST_DIR, 'src') const out = path.join(TEST_DIR, 'out') beforeEach(done => { fse.emptyDir(TEST_DIR, err => { assert.ifError(err) createFixtures(src, done) }) }) afterEach(done => fse.remove(TEST_DIR, done)) it('copies symlinks by default', done => { ncp(src, out, err => { assert.ifError(err) assert.strictEqual(fs.readlinkSync(path.join(out, 'file-symlink')), path.join(src, 'foo')) assert.strictEqual(fs.readlinkSync(path.join(out, 'dir-symlink')), path.join(src, 'dir')) done() }) }) it('copies file contents when dereference=true', done => { ncp(src, out, { dereference: true }, err => { assert.ifError(err) const fileSymlinkPath = path.join(out, 'file-symlink') assert.ok(fs.lstatSync(fileSymlinkPath).isFile()) assert.strictEqual(fs.readFileSync(fileSymlinkPath, 'utf8'), 'foo contents') const dirSymlinkPath = path.join(out, 'dir-symlink') assert.ok(fs.lstatSync(dirSymlinkPath).isDirectory()) assert.deepStrictEqual(fs.readdirSync(dirSymlinkPath), ['bar']) done() }) }) }) function createFixtures (srcDir, callback) { fs.mkdir(srcDir, err => { if (err) return callback(err) // note: third parameter in symlinkSync is type e.g. 'file' or 'dir' // https://nodejs.org/api/fs.html#fs_fs_symlink_srcpath_dstpath_type_callback try { const fooFile = path.join(srcDir, 'foo') const fooFileLink = path.join(srcDir, 'file-symlink') fs.writeFileSync(fooFile, 'foo contents') fs.symlinkSync(fooFile, fooFileLink, 'file') const dir = path.join(srcDir, 'dir') const dirFile = path.join(dir, 'bar') const dirLink = path.join(srcDir, 'dir-symlink') fs.mkdirSync(dir) fs.writeFileSync(dirFile, 'bar contents') fs.symlinkSync(dir, dirLink, 'dir') } catch (err) { callback(err) } callback() }) } ================================================ FILE: lib/copy/copy-sync.js ================================================ 'use strict' const fs = require('graceful-fs') const path = require('path') const mkdirsSync = require('../mkdirs').mkdirsSync const utimesMillisSync = require('../util/utimes').utimesMillisSync const stat = require('../util/stat') function copySync (src, dest, opts) { if (typeof opts === 'function') { opts = { filter: opts } } opts = opts || {} opts.clobber = 'clobber' in opts ? !!opts.clobber : true // default to true for now opts.overwrite = 'overwrite' in opts ? !!opts.overwrite : opts.clobber // overwrite falls back to clobber // Warn about using preserveTimestamps on 32-bit node if (opts.preserveTimestamps && process.arch === 'ia32') { process.emitWarning( 'Using the preserveTimestamps option in 32-bit node is not recommended;\n\n' + '\tsee https://github.com/jprichardson/node-fs-extra/issues/269', 'Warning', 'fs-extra-WARN0002' ) } const { srcStat, destStat } = stat.checkPathsSync(src, dest, 'copy', opts) stat.checkParentPathsSync(src, srcStat, dest, 'copy') if (opts.filter && !opts.filter(src, dest)) return const destParent = path.dirname(dest) if (!fs.existsSync(destParent)) mkdirsSync(destParent) return getStats(destStat, src, dest, opts) } function getStats (destStat, src, dest, opts) { const statSync = opts.dereference ? fs.statSync : fs.lstatSync const srcStat = statSync(src) if (srcStat.isDirectory()) return onDir(srcStat, destStat, src, dest, opts) else if (srcStat.isFile() || srcStat.isCharacterDevice() || srcStat.isBlockDevice()) return onFile(srcStat, destStat, src, dest, opts) else if (srcStat.isSymbolicLink()) return onLink(destStat, src, dest, opts) else if (srcStat.isSocket()) throw new Error(`Cannot copy a socket file: ${src}`) else if (srcStat.isFIFO()) throw new Error(`Cannot copy a FIFO pipe: ${src}`) throw new Error(`Unknown file: ${src}`) } function onFile (srcStat, destStat, src, dest, opts) { if (!destStat) return copyFile(srcStat, src, dest, opts) return mayCopyFile(srcStat, src, dest, opts) } function mayCopyFile (srcStat, src, dest, opts) { if (opts.overwrite) { fs.unlinkSync(dest) return copyFile(srcStat, src, dest, opts) } else if (opts.errorOnExist) { throw new Error(`'${dest}' already exists`) } } function copyFile (srcStat, src, dest, opts) { fs.copyFileSync(src, dest) if (opts.preserveTimestamps) handleTimestamps(srcStat.mode, src, dest) return setDestMode(dest, srcStat.mode) } function handleTimestamps (srcMode, src, dest) { // Make sure the file is writable before setting the timestamp // otherwise open fails with EPERM when invoked with 'r+' // (through utimes call) if (fileIsNotWritable(srcMode)) makeFileWritable(dest, srcMode) return setDestTimestamps(src, dest) } function fileIsNotWritable (srcMode) { return (srcMode & 0o200) === 0 } function makeFileWritable (dest, srcMode) { return setDestMode(dest, srcMode | 0o200) } function setDestMode (dest, srcMode) { return fs.chmodSync(dest, srcMode) } function setDestTimestamps (src, dest) { // The initial srcStat.atime cannot be trusted // because it is modified by the read(2) system call // (See https://nodejs.org/api/fs.html#fs_stat_time_values) const updatedSrcStat = fs.statSync(src) return utimesMillisSync(dest, updatedSrcStat.atime, updatedSrcStat.mtime) } function onDir (srcStat, destStat, src, dest, opts) { if (!destStat) return mkDirAndCopy(srcStat.mode, src, dest, opts) return copyDir(src, dest, opts) } function mkDirAndCopy (srcMode, src, dest, opts) { fs.mkdirSync(dest) copyDir(src, dest, opts) return setDestMode(dest, srcMode) } function copyDir (src, dest, opts) { const dir = fs.opendirSync(src) try { let dirent while ((dirent = dir.readSync()) !== null) { copyDirItem(dirent.name, src, dest, opts) } } finally { dir.closeSync() } } function copyDirItem (item, src, dest, opts) { const srcItem = path.join(src, item) const destItem = path.join(dest, item) if (opts.filter && !opts.filter(srcItem, destItem)) return const { destStat } = stat.checkPathsSync(srcItem, destItem, 'copy', opts) return getStats(destStat, srcItem, destItem, opts) } function onLink (destStat, src, dest, opts) { let resolvedSrc = fs.readlinkSync(src) if (opts.dereference) { resolvedSrc = path.resolve(process.cwd(), resolvedSrc) } if (!destStat) { return fs.symlinkSync(resolvedSrc, dest) } else { let resolvedDest try { resolvedDest = fs.readlinkSync(dest) } catch (err) { // dest exists and is a regular file or directory, // Windows may throw UNKNOWN error. If dest already exists, // fs throws error anyway, so no need to guard against it here. if (err.code === 'EINVAL' || err.code === 'UNKNOWN') return fs.symlinkSync(resolvedSrc, dest) throw err } if (opts.dereference) { resolvedDest = path.resolve(process.cwd(), resolvedDest) } // If both symlinks resolve to the same target, they are still distinct symlinks // that can be copied/overwritten. Only check subdirectory constraints when // the resolved paths are different. if (resolvedSrc !== resolvedDest) { if (stat.isSrcSubdir(resolvedSrc, resolvedDest)) { throw new Error(`Cannot copy '${resolvedSrc}' to a subdirectory of itself, '${resolvedDest}'.`) } // prevent copy if src is a subdir of dest since unlinking // dest in this case would result in removing src contents // and therefore a broken symlink would be created. if (stat.isSrcSubdir(resolvedDest, resolvedSrc)) { throw new Error(`Cannot overwrite '${resolvedDest}' with '${resolvedSrc}'.`) } } return copyLink(resolvedSrc, dest) } } function copyLink (resolvedSrc, dest) { fs.unlinkSync(dest) return fs.symlinkSync(resolvedSrc, dest) } module.exports = copySync ================================================ FILE: lib/copy/copy.js ================================================ 'use strict' const fs = require('../fs') const path = require('path') const { mkdirs } = require('../mkdirs') const { pathExists } = require('../path-exists') const { utimesMillis } = require('../util/utimes') const stat = require('../util/stat') const { asyncIteratorConcurrentProcess } = require('../util/async') async function copy (src, dest, opts = {}) { if (typeof opts === 'function') { opts = { filter: opts } } opts.clobber = 'clobber' in opts ? !!opts.clobber : true // default to true for now opts.overwrite = 'overwrite' in opts ? !!opts.overwrite : opts.clobber // overwrite falls back to clobber // Warn about using preserveTimestamps on 32-bit node if (opts.preserveTimestamps && process.arch === 'ia32') { process.emitWarning( 'Using the preserveTimestamps option in 32-bit node is not recommended;\n\n' + '\tsee https://github.com/jprichardson/node-fs-extra/issues/269', 'Warning', 'fs-extra-WARN0001' ) } const { srcStat, destStat } = await stat.checkPaths(src, dest, 'copy', opts) await stat.checkParentPaths(src, srcStat, dest, 'copy') const include = await runFilter(src, dest, opts) if (!include) return // check if the parent of dest exists, and create it if it doesn't exist const destParent = path.dirname(dest) const dirExists = await pathExists(destParent) if (!dirExists) { await mkdirs(destParent) } await getStatsAndPerformCopy(destStat, src, dest, opts) } async function runFilter (src, dest, opts) { if (!opts.filter) return true return opts.filter(src, dest) } async function getStatsAndPerformCopy (destStat, src, dest, opts) { const statFn = opts.dereference ? fs.stat : fs.lstat const srcStat = await statFn(src) if (srcStat.isDirectory()) return onDir(srcStat, destStat, src, dest, opts) if ( srcStat.isFile() || srcStat.isCharacterDevice() || srcStat.isBlockDevice() ) return onFile(srcStat, destStat, src, dest, opts) if (srcStat.isSymbolicLink()) return onLink(destStat, src, dest, opts) if (srcStat.isSocket()) throw new Error(`Cannot copy a socket file: ${src}`) if (srcStat.isFIFO()) throw new Error(`Cannot copy a FIFO pipe: ${src}`) throw new Error(`Unknown file: ${src}`) } async function onFile (srcStat, destStat, src, dest, opts) { if (!destStat) return copyFile(srcStat, src, dest, opts) if (opts.overwrite) { await fs.unlink(dest) return copyFile(srcStat, src, dest, opts) } if (opts.errorOnExist) { throw new Error(`'${dest}' already exists`) } } async function copyFile (srcStat, src, dest, opts) { await fs.copyFile(src, dest) if (opts.preserveTimestamps) { // Make sure the file is writable before setting the timestamp // otherwise open fails with EPERM when invoked with 'r+' // (through utimes call) if (fileIsNotWritable(srcStat.mode)) { await makeFileWritable(dest, srcStat.mode) } // Set timestamps and mode correspondingly // Note that The initial srcStat.atime cannot be trusted // because it is modified by the read(2) system call // (See https://nodejs.org/api/fs.html#fs_stat_time_values) const updatedSrcStat = await fs.stat(src) await utimesMillis(dest, updatedSrcStat.atime, updatedSrcStat.mtime) } return fs.chmod(dest, srcStat.mode) } function fileIsNotWritable (srcMode) { return (srcMode & 0o200) === 0 } function makeFileWritable (dest, srcMode) { return fs.chmod(dest, srcMode | 0o200) } async function onDir (srcStat, destStat, src, dest, opts) { // the dest directory might not exist, create it if (!destStat) { await fs.mkdir(dest) } // iterate through the files in the current directory to copy everything await asyncIteratorConcurrentProcess(await fs.opendir(src), async (item) => { const srcItem = path.join(src, item.name) const destItem = path.join(dest, item.name) const include = await runFilter(srcItem, destItem, opts) // only copy the item if it matches the filter function if (include) { const { destStat } = await stat.checkPaths(srcItem, destItem, 'copy', opts) // If the item is a copyable file, `getStatsAndPerformCopy` will copy it // If the item is a directory, `getStatsAndPerformCopy` will call `onDir` recursively await getStatsAndPerformCopy(destStat, srcItem, destItem, opts) } }) if (!destStat) { await fs.chmod(dest, srcStat.mode) } } async function onLink (destStat, src, dest, opts) { let resolvedSrc = await fs.readlink(src) if (opts.dereference) { resolvedSrc = path.resolve(process.cwd(), resolvedSrc) } if (!destStat) { return fs.symlink(resolvedSrc, dest) } let resolvedDest = null try { resolvedDest = await fs.readlink(dest) } catch (e) { // dest exists and is a regular file or directory, // Windows may throw UNKNOWN error. If dest already exists, // fs throws error anyway, so no need to guard against it here. if (e.code === 'EINVAL' || e.code === 'UNKNOWN') return fs.symlink(resolvedSrc, dest) throw e } if (opts.dereference) { resolvedDest = path.resolve(process.cwd(), resolvedDest) } // If both symlinks resolve to the same target, they are still distinct symlinks // that can be copied/overwritten. Only check subdirectory constraints when // the resolved paths are different. if (resolvedSrc !== resolvedDest) { if (stat.isSrcSubdir(resolvedSrc, resolvedDest)) { throw new Error(`Cannot copy '${resolvedSrc}' to a subdirectory of itself, '${resolvedDest}'.`) } // do not copy if src is a subdir of dest since unlinking // dest in this case would result in removing src contents // and therefore a broken symlink would be created. if (stat.isSrcSubdir(resolvedDest, resolvedSrc)) { throw new Error(`Cannot overwrite '${resolvedDest}' with '${resolvedSrc}'.`) } } // copy the link await fs.unlink(dest) return fs.symlink(resolvedSrc, dest) } module.exports = copy ================================================ FILE: lib/copy/index.js ================================================ 'use strict' const u = require('universalify').fromPromise module.exports = { copy: u(require('./copy')), copySync: require('./copy-sync') } ================================================ FILE: lib/empty/__tests__/empty-dir-sync.test.js ================================================ 'use strict' const fs = require('fs') const os = require('os') const fse = require('../..') const path = require('path') const assert = require('assert') /* global afterEach, beforeEach, describe, it */ describe('+ emptyDir()', () => { let TEST_DIR beforeEach(() => { TEST_DIR = path.join(os.tmpdir(), 'test-fs-extra', 'empty-dir') if (fs.existsSync(TEST_DIR)) { fse.removeSync(TEST_DIR) } fse.ensureDirSync(TEST_DIR) }) afterEach(done => fse.remove(TEST_DIR, done)) describe('> when directory exists and contains items', () => { it('should delete all of the items', () => { // verify nothing assert.strictEqual(fs.readdirSync(TEST_DIR).length, 0) fse.ensureFileSync(path.join(TEST_DIR, 'some-file')) fse.ensureFileSync(path.join(TEST_DIR, 'some-file-2')) fse.ensureDirSync(path.join(TEST_DIR, 'some-dir')) assert.strictEqual(fs.readdirSync(TEST_DIR).length, 3) fse.emptyDirSync(TEST_DIR) assert.strictEqual(fs.readdirSync(TEST_DIR).length, 0) }) }) describe('> when directory exists and contains no items', () => { it('should do nothing', () => { assert.strictEqual(fs.readdirSync(TEST_DIR).length, 0) fse.emptyDirSync(TEST_DIR) assert.strictEqual(fs.readdirSync(TEST_DIR).length, 0) }) }) describe('> when directory does not exist', () => { it('should create it', () => { fse.removeSync(TEST_DIR) assert(!fs.existsSync(TEST_DIR)) fse.emptyDirSync(TEST_DIR) assert.strictEqual(fs.readdirSync(TEST_DIR).length, 0) }) }) }) ================================================ FILE: lib/empty/__tests__/empty-dir.test.js ================================================ 'use strict' const fs = require('fs') const os = require('os') const fse = require('../..') const path = require('path') const assert = require('assert') /* global afterEach, beforeEach, describe, it */ describe('+ emptyDir()', () => { let TEST_DIR beforeEach(() => { TEST_DIR = path.join(os.tmpdir(), 'test-fs-extra', 'empty-dir') if (fs.existsSync(TEST_DIR)) { fse.removeSync(TEST_DIR) } fse.ensureDirSync(TEST_DIR) }) afterEach(done => fse.remove(TEST_DIR, done)) describe('> when directory exists and contains items', () => { it('should delete all of the items', done => { // verify nothing assert.strictEqual(fs.readdirSync(TEST_DIR).length, 0) fse.ensureFileSync(path.join(TEST_DIR, 'some-file')) fse.ensureFileSync(path.join(TEST_DIR, 'some-file-2')) fse.ensureDirSync(path.join(TEST_DIR, 'some-dir')) assert.strictEqual(fs.readdirSync(TEST_DIR).length, 3) fse.emptyDir(TEST_DIR, err => { assert.ifError(err) assert.strictEqual(fs.readdirSync(TEST_DIR).length, 0) done() }) }) }) describe('> when directory exists and contains no items', () => { it('should do nothing', done => { assert.strictEqual(fs.readdirSync(TEST_DIR).length, 0) fse.emptyDir(TEST_DIR, err => { assert.ifError(err) assert.strictEqual(fs.readdirSync(TEST_DIR).length, 0) done() }) }) }) describe('> when directory does not exist', () => { it('should create it', done => { fse.removeSync(TEST_DIR) assert(!fs.existsSync(TEST_DIR)) fse.emptyDir(TEST_DIR, err => { assert.ifError(err) assert.strictEqual(fs.readdirSync(TEST_DIR).length, 0) done() }) }) }) }) ================================================ FILE: lib/empty/index.js ================================================ 'use strict' const u = require('universalify').fromPromise const fs = require('../fs') const path = require('path') const mkdir = require('../mkdirs') const remove = require('../remove') const emptyDir = u(async function emptyDir (dir) { let items try { items = await fs.readdir(dir) } catch { return mkdir.mkdirs(dir) } return Promise.all(items.map(item => remove.remove(path.join(dir, item)))) }) function emptyDirSync (dir) { let items try { items = fs.readdirSync(dir) } catch { return mkdir.mkdirsSync(dir) } items.forEach(item => { item = path.join(dir, item) remove.removeSync(item) }) } module.exports = { emptyDirSync, emptydirSync: emptyDirSync, emptyDir, emptydir: emptyDir } ================================================ FILE: lib/ensure/__tests__/create.test.js ================================================ 'use strict' const fs = require('fs') const os = require('os') const fse = require('../..') const path = require('path') const assert = require('assert') /* global afterEach, beforeEach, describe, it */ describe('fs-extra', () => { let TEST_DIR beforeEach(done => { TEST_DIR = path.join(os.tmpdir(), 'fs-extra', 'create') fse.emptyDir(TEST_DIR, done) }) afterEach(done => fse.remove(TEST_DIR, done)) describe('+ createFile', () => { describe('> when the file and directory does not exist', () => { it('should create the file', done => { const file = path.join(TEST_DIR, Math.random() + 't-ne', Math.random() + '.txt') assert(!fs.existsSync(file)) fse.createFile(file, err => { assert.ifError(err) assert(fs.existsSync(file)) done() }) }) }) describe('> when the file does exist', () => { it('should not modify the file', done => { const file = path.join(TEST_DIR, Math.random() + 't-e', Math.random() + '.txt') fse.mkdirsSync(path.dirname(file)) fs.writeFileSync(file, 'hello world') fse.createFile(file, err => { assert.ifError(err) assert.strictEqual(fs.readFileSync(file, 'utf8'), 'hello world') done() }) }) it('should give clear error if node in directory tree is a file', done => { const existingFile = path.join(TEST_DIR, Math.random() + 'ts-e', Math.random() + '.txt') fse.mkdirsSync(path.dirname(existingFile)) fs.writeFileSync(existingFile, '') const file = path.join(existingFile, Math.random() + '.txt') fse.createFile(file, err => { assert.strictEqual(err.code, 'ENOTDIR') done() }) }) }) }) describe('+ createFileSync', () => { describe('> when the file and directory does not exist', () => { it('should create the file', () => { const file = path.join(TEST_DIR, Math.random() + 'ts-ne', Math.random() + '.txt') assert(!fs.existsSync(file)) fse.createFileSync(file) assert(fs.existsSync(file)) }) }) describe('> when the file does exist', () => { it('should not modify the file', () => { const file = path.join(TEST_DIR, Math.random() + 'ts-e', Math.random() + '.txt') fse.mkdirsSync(path.dirname(file)) fs.writeFileSync(file, 'hello world') fse.createFileSync(file) assert.strictEqual(fs.readFileSync(file, 'utf8'), 'hello world') }) it('should give clear error if node in directory tree is a file', () => { const existingFile = path.join(TEST_DIR, Math.random() + 'ts-e', Math.random() + '.txt') fse.mkdirsSync(path.dirname(existingFile)) fs.writeFileSync(existingFile, '') const file = path.join(existingFile, Math.random() + '.txt') try { fse.createFileSync(file) assert.fail() } catch (err) { assert.strictEqual(err.code, 'ENOTDIR') } }) }) }) }) ================================================ FILE: lib/ensure/__tests__/ensure.test.js ================================================ 'use strict' const fs = require('fs') const os = require('os') const fse = require('../..') const path = require('path') const assert = require('assert') /* global afterEach, beforeEach, describe, it */ describe('fs-extra', () => { let TEST_DIR beforeEach(done => { TEST_DIR = path.join(os.tmpdir(), 'fs-extra', 'ensure') fse.emptyDir(TEST_DIR, done) }) afterEach(done => fse.remove(TEST_DIR, done)) describe('+ ensureFile()', () => { describe('> when file exists', () => { it('should not do anything', done => { const file = path.join(TEST_DIR, 'file.txt') fs.writeFileSync(file, 'blah') assert(fs.existsSync(file)) fse.ensureFile(file, err => { assert.ifError(err) assert(fs.existsSync(file)) done() }) }) }) describe('> when file does not exist', () => { it('should create the file', done => { const file = path.join(TEST_DIR, 'dir/that/does/not/exist', 'file.txt') assert(!fs.existsSync(file)) fse.ensureFile(file, err => { assert.ifError(err) assert(fs.existsSync(file)) done() }) }) }) describe('> when there is a directory at that path', () => { it('should error', done => { const p = path.join(TEST_DIR, 'somedir') fs.mkdirSync(p) fse.ensureFile(p, err => { assert(err) assert.strictEqual(err.code, 'EISDIR') done() }) }) }) }) describe('+ ensureFileSync()', () => { describe('> when file exists', () => { it('should not do anything', () => { const file = path.join(TEST_DIR, 'file.txt') fs.writeFileSync(file, 'blah') assert(fs.existsSync(file)) fse.ensureFileSync(file) assert(fs.existsSync(file)) }) }) describe('> when file does not exist', () => { it('should create the file', () => { const file = path.join(TEST_DIR, 'dir/that/does/not/exist', 'file.txt') assert(!fs.existsSync(file)) fse.ensureFileSync(file) assert(fs.existsSync(file)) }) }) describe('> when there is a directory at that path', () => { it('should error', () => { const p = path.join(TEST_DIR, 'somedir2') fs.mkdirSync(p) assert.throws(() => { try { fse.ensureFileSync(p) } catch (e) { assert.strictEqual(e.code, 'EISDIR') throw e } }) }) }) }) describe('+ ensureDir()', () => { describe('> when dir exists', () => { it('should not do anything', done => { const dir = path.join(TEST_DIR, 'dir/does/not/exist') fse.mkdirpSync(dir) assert(fs.existsSync(dir)) fse.ensureDir(dir, err => { assert.ifError(err) assert(fs.existsSync(dir)) done() }) }) }) describe('> when dir does not exist', () => { it('should create the dir', done => { const dir = path.join(TEST_DIR, 'dir/that/does/not/exist') assert(!fs.existsSync(dir)) fse.ensureDir(dir, err => { assert.ifError(err) assert(fs.existsSync(dir)) done() }) }) }) }) describe('+ ensureDirSync()', () => { describe('> when dir exists', () => { it('should not do anything', () => { const dir = path.join(TEST_DIR, 'dir/does/not/exist') fse.mkdirpSync(dir) assert(fs.existsSync(dir)) fse.ensureDirSync(dir) assert(fs.existsSync(dir)) }) }) describe('> when dir does not exist', () => { it('should create the dir', () => { const dir = path.join(TEST_DIR, 'dir/that/does/not/exist') assert(!fs.existsSync(dir)) fse.ensureDirSync(dir) assert(fs.existsSync(dir)) }) }) }) }) ================================================ FILE: lib/ensure/__tests__/link.test.js ================================================ 'use strict' const CWD = process.cwd() const fs = require('graceful-fs') const os = require('os') const fse = require('../..') const path = require('path') const assert = require('assert') const ensureLink = fse.ensureLink const ensureLinkSync = fse.ensureLinkSync /* global afterEach, beforeEach, describe, it, after, before */ describe('fse-ensure-link', () => { const TEST_DIR = path.join(os.tmpdir(), 'fs-extra', 'ensure-symlink') const tests = [ // [[srcpath, dstpath], fs.link expect, ensureLink expect] [['./foo.txt', './link.txt'], 'file-success', 'file-success'], [['./foo.txt', './dir-foo/link.txt'], 'file-success', 'file-success'], [['./foo.txt', './empty-dir/link.txt'], 'file-success', 'file-success'], [['./foo.txt', './real-alpha/link.txt'], 'file-success', 'file-success'], [['./foo.txt', './real-alpha/real-beta/link.txt'], 'file-success', 'file-success'], [['./foo.txt', './real-alpha/real-beta/real-gamma/link.txt'], 'file-success', 'file-success'], [['./foo.txt', './alpha/link.txt'], 'file-error', 'file-success'], [['./foo.txt', './alpha/beta/link.txt'], 'file-error', 'file-success'], [['./foo.txt', './alpha/beta/gamma/link.txt'], 'file-error', 'file-success'], [['./foo.txt', './link-foo.txt'], 'file-error', 'file-success'], [['./dir-foo/foo.txt', './link-foo.txt'], 'file-error', 'file-error'], [['./missing.txt', './link.txt'], 'file-error', 'file-error'], [['./missing.txt', './missing-dir/link.txt'], 'file-error', 'file-error'], [['./foo.txt', './link.txt'], 'file-success', 'file-success'], [['./dir-foo/foo.txt', './link.txt'], 'file-success', 'file-success'], [['./missing.txt', './link.txt'], 'file-error', 'file-error'], [['../foo.txt', './link.txt'], 'file-error', 'file-error'], [['../dir-foo/foo.txt', './link.txt'], 'file-error', 'file-error'], // error is thrown if destination path exists [['./foo.txt', './dir-foo/foo.txt'], 'file-error', 'file-error'], [[path.resolve(path.join(TEST_DIR, './foo.txt')), './link.txt'], 'file-success', 'file-success'], [[path.resolve(path.join(TEST_DIR, './dir-foo/foo.txt')), './link.txt'], 'file-success', 'file-success'], [[path.resolve(path.join(TEST_DIR, './missing.txt')), './link.txt'], 'file-error', 'file-error'], [[path.resolve(path.join(TEST_DIR, '../foo.txt')), './link.txt'], 'file-error', 'file-error'], [[path.resolve(path.join(TEST_DIR, '../dir-foo/foo.txt')), './link.txt'], 'file-error', 'file-error'] ] before(() => { fse.emptyDirSync(TEST_DIR) process.chdir(TEST_DIR) }) beforeEach(() => { fs.writeFileSync('./foo.txt', 'foo\n') fse.mkdirsSync('empty-dir') fse.mkdirsSync('dir-foo') fs.writeFileSync('dir-foo/foo.txt', 'dir-foo\n') fse.mkdirsSync('dir-bar') fs.writeFileSync('dir-bar/bar.txt', 'dir-bar\n') fse.mkdirsSync('real-alpha/real-beta/real-gamma') fs.linkSync('foo.txt', 'link-foo.txt') }) afterEach(done => fse.emptyDir(TEST_DIR, done)) after(() => { process.chdir(CWD) fse.removeSync(TEST_DIR) }) function fileSuccess (args, fn) { const srcpath = args[0] const dstpath = args[1] it(`should create link file using src ${srcpath} and dst ${dstpath}`, done => { const callback = err => { if (err) return done(err) const srcContent = fs.readFileSync(srcpath, 'utf8') const dstDir = path.dirname(dstpath) const dstBasename = path.basename(dstpath) const isSymlink = fs.lstatSync(dstpath).isFile() const dstContent = fs.readFileSync(dstpath, 'utf8') const dstDirContents = fs.readdirSync(dstDir) assert.strictEqual(isSymlink, true) assert.strictEqual(srcContent, dstContent) assert(dstDirContents.indexOf(dstBasename) >= 0) return done() } args.push(callback) return fn(...args) }) } function fileError (args, fn) { const srcpath = args[0] const dstpath = args[1] it(`should return error when creating link file using src ${srcpath} and dst ${dstpath}`, done => { const dstdirExistsBefore = fs.existsSync(path.dirname(dstpath)) const callback = err => { assert.strictEqual(err instanceof Error, true) // ensure that directories aren't created if there's an error const dstdirExistsAfter = fs.existsSync(path.dirname(dstpath)) assert.strictEqual(dstdirExistsBefore, dstdirExistsAfter) return done() } args.push(callback) return fn(...args) }) } function fileSuccessSync (args, fn) { const srcpath = args[0] const dstpath = args[1] it(`should create link file using src ${srcpath} and dst ${dstpath}`, () => { fn(...args) const srcContent = fs.readFileSync(srcpath, 'utf8') const dstDir = path.dirname(dstpath) const dstBasename = path.basename(dstpath) const isSymlink = fs.lstatSync(dstpath).isFile() const dstContent = fs.readFileSync(dstpath, 'utf8') const dstDirContents = fs.readdirSync(dstDir) assert.strictEqual(isSymlink, true) assert.strictEqual(srcContent, dstContent) assert(dstDirContents.indexOf(dstBasename) >= 0) }) } function fileErrorSync (args, fn) { const srcpath = args[0] const dstpath = args[1] it(`should throw error using src ${srcpath} and dst ${dstpath}`, () => { // will fail if dstdir is created and there's an error const dstdirExistsBefore = fs.existsSync(path.dirname(dstpath)) let err = null try { fn(...args) } catch (e) { err = e } assert.strictEqual(err instanceof Error, true) const dstdirExistsAfter = fs.existsSync(path.dirname(dstpath)) assert.strictEqual(dstdirExistsBefore, dstdirExistsAfter) }) } describe('fs.link()', () => { const fn = fs.link tests.forEach(test => { const args = test[0].slice(0) const nativeBehavior = test[1] // const newBehavior = test[2] if (nativeBehavior === 'file-success') fileSuccess(args, fn) if (nativeBehavior === 'file-error') fileError(args, fn) }) }) describe('ensureLink()', () => { const fn = ensureLink tests.forEach(test => { const args = test[0].slice(0) // const nativeBehavior = test[1] const newBehavior = test[2] if (newBehavior === 'file-success') fileSuccess(args, fn) if (newBehavior === 'file-error') fileError(args, fn) }) }) describe('ensureLink() promise support', () => { tests.filter(test => test[2] === 'file-success').forEach(test => { const args = test[0].slice(0) const srcpath = args[0] const dstpath = args[1] it(`should create link file using src ${srcpath} and dst ${dstpath}`, () => { return ensureLink(srcpath, dstpath) .then(() => { const srcContent = fs.readFileSync(srcpath, 'utf8') const dstDir = path.dirname(dstpath) const dstBasename = path.basename(dstpath) const isSymlink = fs.lstatSync(dstpath).isFile() const dstContent = fs.readFileSync(dstpath, 'utf8') const dstDirContents = fs.readdirSync(dstDir) assert.strictEqual(isSymlink, true) assert.strictEqual(srcContent, dstContent) assert(dstDirContents.indexOf(dstBasename) >= 0) }) }) }) }) describe('fs.linkSync()', () => { const fn = fs.linkSync tests.forEach(test => { const args = test[0].slice(0) const nativeBehavior = test[1] // const newBehavior = test[2] if (nativeBehavior === 'file-success') fileSuccessSync(args, fn) if (nativeBehavior === 'file-error') fileErrorSync(args, fn) }) }) describe('ensureLinkSync()', () => { const fn = ensureLinkSync tests.forEach(test => { const args = test[0].slice(0) // const nativeBehavior = test[1] const newBehavior = test[2] if (newBehavior === 'file-success') fileSuccessSync(args, fn) if (newBehavior === 'file-error') fileErrorSync(args, fn) }) }) }) ================================================ FILE: lib/ensure/__tests__/symlink-paths.test.js ================================================ 'use strict' const CWD = process.cwd() const fs = require('graceful-fs') const os = require('os') const fse = require('../..') const path = require('path') const assert = require('assert') const _symlinkPaths = require('../symlink-paths') const symlinkPaths = _symlinkPaths.symlinkPaths const symlinkPathsSync = _symlinkPaths.symlinkPathsSync const TEST_DIR = path.join(os.tmpdir(), 'fs-extra', 'ensure-symlink') /* global afterEach, beforeEach, describe, it, after, before */ describe('symlink-type', () => { before(() => { fse.emptyDirSync(TEST_DIR) process.chdir(TEST_DIR) }) beforeEach(() => { fs.writeFileSync('./foo.txt', 'foo\n') fse.mkdirsSync('./empty-dir') fse.mkdirsSync('./dir-foo') fs.writeFileSync('./dir-foo/foo.txt', 'dir-foo\n') fse.mkdirsSync('./dir-bar') fs.writeFileSync('./dir-bar/bar.txt', 'dir-bar\n') fse.mkdirsSync('./real-alpha/real-beta/real-gamma') }) afterEach(done => fse.emptyDir(TEST_DIR, done)) after(() => { process.chdir(CWD) fse.removeSync(TEST_DIR) }) const tests = [ [['foo.txt', 'symlink.txt'], { toCwd: 'foo.txt', toDst: 'foo.txt' }], // smart && nodestyle [['foo.txt', 'empty-dir/symlink.txt'], { toCwd: 'foo.txt', toDst: '../foo.txt' }], // smart [['../foo.txt', 'empty-dir/symlink.txt'], { toCwd: 'foo.txt', toDst: '../foo.txt' }], // nodestyle [['foo.txt', 'dir-bar/symlink.txt'], { toCwd: 'foo.txt', toDst: '../foo.txt' }], // smart [['../foo.txt', 'dir-bar/symlink.txt'], { toCwd: 'foo.txt', toDst: '../foo.txt' }], // nodestyle // this is to preserve node's symlink capability these arguments say create // a link to 'dir-foo/foo.txt' this works because it exists this is unlike // the previous example with 'empty-dir' because 'empty-dir/foo.txt' does not exist. [['foo.txt', 'dir-foo/symlink.txt'], { toCwd: 'dir-foo/foo.txt', toDst: 'foo.txt' }], // nodestyle [['foo.txt', 'real-alpha/real-beta/real-gamma/symlink.txt'], { toCwd: 'foo.txt', toDst: '../../../foo.txt' }] ] // formats paths to pass on multiple operating systems tests.forEach(test => { test[0][0] = path.join(test[0][0]) test[0][1] = path.join(test[0][1]) test[1] = { toCwd: path.join(test[1].toCwd), toDst: path.join(test[1].toDst) } }) describe('symlinkPaths()', () => { tests.forEach(test => { const args = test[0].slice(0) const expectedRelativePaths = test[1] it(`should return '${JSON.stringify(expectedRelativePaths)}' when src '${args[0]}' and dst is '${args[1]}'`, done => { const callback = (err, relativePaths) => { if (err) done(err) assert.deepStrictEqual(relativePaths, expectedRelativePaths) done() } args.push(callback) return symlinkPaths(...args) }) }) }) describe('symlinkPathsSync()', () => { tests.forEach(test => { const args = test[0].slice(0) const expectedRelativePaths = test[1] it(`should return '${JSON.stringify(expectedRelativePaths)}' when src '${args[0]}' and dst is '${args[1]}'`, () => { const relativePaths = symlinkPathsSync(...args) assert.deepStrictEqual(relativePaths, expectedRelativePaths) }) }) }) }) ================================================ FILE: lib/ensure/__tests__/symlink-type.test.js ================================================ 'use strict' const CWD = process.cwd() const fs = require('graceful-fs') const os = require('os') const fse = require('../..') const path = require('path') const assert = require('assert') const _symlinkType = require('../symlink-type') const symlinkType = _symlinkType.symlinkType const symlinkTypeSync = _symlinkType.symlinkTypeSync const TEST_DIR = path.join(os.tmpdir(), 'fs-extra', 'ensure-symlink') /* global afterEach, beforeEach, describe, it, after, before */ describe('symlink-type', () => { before(() => { fse.emptyDirSync(TEST_DIR) process.chdir(TEST_DIR) }) beforeEach(() => { fs.writeFileSync('./foo.txt', 'foo\n') fse.mkdirsSync('./empty-dir') fse.mkdirsSync('./dir-foo') fs.writeFileSync('./dir-foo/foo.txt', 'dir-foo\n') fse.mkdirsSync('./dir-bar') fs.writeFileSync('./dir-bar/bar.txt', 'dir-bar\n') fse.mkdirsSync('./real-alpha/real-beta/real-gamma') }) afterEach(done => fse.emptyDir(TEST_DIR, done)) after(() => { process.chdir(CWD) fse.removeSync(TEST_DIR) }) const tests = { success: [ // [{arguments} [srcpath, dirpath, [type] , result] // smart file type checking [['./foo.txt'], 'file'], [['./empty-dir'], 'dir'], [['./dir-foo/foo.txt'], 'file'], [['./dir-bar'], 'dir'], [['./dir-bar/bar.txt'], 'file'], [['./real-alpha/real-beta/real-gamma'], 'dir'], // force dir [['./foo.txt', 'dir'], 'dir'], [['./empty-dir', 'dir'], 'dir'], [['./dir-foo/foo.txt', 'dir'], 'dir'], [['./dir-bar', 'dir'], 'dir'], [['./dir-bar/bar.txt', 'dir'], 'dir'], [['./real-alpha/real-beta/real-gamma', 'dir'], 'dir'], // force file [['./foo.txt', 'file'], 'file'], [['./empty-dir', 'file'], 'file'], [['./dir-foo/foo.txt', 'file'], 'file'], [['./dir-bar', 'file'], 'file'], [['./dir-bar/bar.txt', 'file'], 'file'], [['./real-alpha/real-beta/real-gamma', 'file'], 'file'], // default for files or dirs that don't exist is file [['./missing.txt'], 'file'], [['./missing'], 'file'], [['./missing.txt'], 'file'], [['./missing'], 'file'], [['./empty-dir/missing.txt'], 'file'], [['./empty-dir/missing'], 'file'], [['./empty-dir/missing.txt'], 'file'], [['./empty-dir/missing'], 'file'], // when src doesnt exist and provided type 'file' [['./missing.txt', 'file'], 'file'], [['./missing', 'file'], 'file'], [['./missing.txt', 'file'], 'file'], [['./missing', 'file'], 'file'], [['./empty-dir/missing.txt', 'file'], 'file'], [['./empty-dir/missing', 'file'], 'file'], [['./empty-dir/missing.txt', 'file'], 'file'], [['./empty-dir/missing', 'file'], 'file'], // when src doesnt exist and provided type 'dir' [['./missing.txt', 'dir'], 'dir'], [['./missing', 'dir'], 'dir'], [['./missing.txt', 'dir'], 'dir'], [['./missing', 'dir'], 'dir'], [['./empty-dir/missing.txt', 'dir'], 'dir'], [['./empty-dir/missing', 'dir'], 'dir'], [['./empty-dir/missing.txt', 'dir'], 'dir'], [['./empty-dir/missing', 'dir'], 'dir'] ] } describe('symlinkType()', () => { tests.success.forEach(test => { const args = test[0].slice(0) const expectedType = test[1] it(`should return '${expectedType}' when src '${args[0]}'`, done => { const callback = (err, type) => { if (err) done(err) assert.strictEqual(type, expectedType) done() } args.push(callback) return symlinkType(...args) }) }) }) describe('symlinkTypeSync()', () => { tests.success.forEach(test => { const args = test[0] const expectedType = test[1] it(`should return '${expectedType}' when src '${args[0]}'`, () => { const type = symlinkTypeSync(...args) assert.strictEqual(type, expectedType) }) }) }) }) ================================================ FILE: lib/ensure/__tests__/symlink.test.js ================================================ 'use strict' const CWD = process.cwd() const fs = require('graceful-fs') const os = require('os') const fse = require('../..') const path = require('path') const assert = require('assert') const _symlinkPaths = require('../symlink-paths') const symlinkPathsSync = _symlinkPaths.symlinkPathsSync const ensureSymlink = fse.ensureSymlink const ensureSymlinkSync = fse.ensureSymlinkSync /* global afterEach, beforeEach, describe, it, after, before */ let TEST_DIR describe('fse-ensure-symlink', () => { TEST_DIR = path.join(os.tmpdir(), 'fs-extra', 'ensure-symlink') const tests = [ // [[srcpath, dstpath], fs.symlink expect, fse.ensureSymlink expect] [['./foo.txt', './symlink.txt'], 'file-success', 'file-success'], [['../foo.txt', './empty-dir/symlink.txt'], 'file-success', 'file-success'], [['../foo.txt', './empty-dir/symlink.txt'], 'file-success', 'file-success'], [['./foo.txt', './dir-foo/symlink.txt'], 'file-success', 'file-success'], [['./foo.txt', './empty-dir/symlink.txt'], 'file-broken', 'file-success'], [['./foo.txt', './real-alpha/symlink.txt'], 'file-broken', 'file-success'], [['./foo.txt', './real-alpha/real-beta/symlink.txt'], 'file-broken', 'file-success'], [['./foo.txt', './real-alpha/real-beta/real-gamma/symlink.txt'], 'file-broken', 'file-success'], [['./foo.txt', './alpha/symlink.txt'], 'file-error', 'file-success'], [['./foo.txt', './alpha/beta/symlink.txt'], 'file-error', 'file-success'], [['./foo.txt', './alpha/beta/gamma/symlink.txt'], 'file-error', 'file-success'], [['./foo.txt', './real-symlink.txt'], 'file-error', 'file-success'], [['./dir-foo/foo.txt', './real-symlink.txt'], 'file-error', 'file-error'], [['./missing.txt', './symlink.txt'], 'file-broken', 'file-error'], [['./missing.txt', './missing-dir/symlink.txt'], 'file-error', 'file-error'], // error is thrown if destination path exists [['./foo.txt', './dir-foo/foo.txt'], 'file-error', 'file-error'], [['./dir-foo', './symlink-dir-foo'], 'dir-success', 'dir-success'], [['../dir-bar', './dir-foo/symlink-dir-bar'], 'dir-success', 'dir-success'], [['./dir-bar', './dir-foo/symlink-dir-bar'], 'dir-broken', 'dir-success'], [['./dir-bar', './empty-dir/symlink-dir-bar'], 'dir-broken', 'dir-success'], [['./dir-bar', './real-alpha/symlink-dir-bar'], 'dir-broken', 'dir-success'], [['./dir-bar', './real-alpha/real-beta/symlink-dir-bar'], 'dir-broken', 'dir-success'], [['./dir-bar', './real-alpha/real-beta/real-gamma/symlink-dir-bar'], 'dir-broken', 'dir-success'], [['./dir-foo', './alpha/dir-foo'], 'dir-error', 'dir-success'], [['./dir-foo', './alpha/beta/dir-foo'], 'dir-error', 'dir-success'], [['./dir-foo', './alpha/beta/gamma/dir-foo'], 'dir-error', 'dir-success'], [['./dir-foo', './real-symlink-dir-foo'], 'dir-error', 'dir-success'], [['./dir-bar', './real-symlink-dir-foo'], 'dir-error', 'dir-error'], [['./missing', './dir-foo/symlink-dir-missing'], 'dir-broken', 'dir-error'], // error is thrown if destination path exists [['./dir-foo', './real-alpha/real-beta'], 'dir-error', 'dir-error'], [[path.resolve(path.join(TEST_DIR, './foo.txt')), './symlink.txt'], 'file-success', 'file-success'], [[path.resolve(path.join(TEST_DIR, './dir-foo/foo.txt')), './symlink.txt'], 'file-success', 'file-success'], [[path.resolve(path.join(TEST_DIR, './missing.txt')), './symlink.txt'], 'file-broken', 'file-error'], [[path.resolve(path.join(TEST_DIR, '../foo.txt')), './symlink.txt'], 'file-broken', 'file-error'], [[path.resolve(path.join(TEST_DIR, '../dir-foo/foo.txt')), './symlink.txt'], 'file-broken', 'file-error'] ] before(() => { fse.emptyDirSync(TEST_DIR) process.chdir(TEST_DIR) }) beforeEach(() => { fs.writeFileSync('./foo.txt', 'foo\n') fse.mkdirsSync('empty-dir') fse.mkdirsSync('dir-foo') fs.writeFileSync('dir-foo/foo.txt', 'dir-foo\n') fse.mkdirsSync('dir-bar') fs.writeFileSync('dir-bar/bar.txt', 'dir-bar\n') fse.mkdirsSync('real-alpha/real-beta/real-gamma') fs.symlinkSync('foo.txt', 'real-symlink.txt') fs.symlinkSync('dir-foo', 'real-symlink-dir-foo') }) afterEach(done => fse.emptyDir(TEST_DIR, done)) after(() => { process.chdir(CWD) fse.removeSync(TEST_DIR) }) function fileSuccess (args, fn) { const srcpath = args[0] const dstpath = args[1] it(`should create symlink file using src ${srcpath} and dst ${dstpath}`, done => { const callback = err => { if (err) return done(err) const relative = symlinkPathsSync(srcpath, dstpath) const srcContent = fs.readFileSync(relative.toCwd, 'utf8') const dstDir = path.dirname(dstpath) const dstBasename = path.basename(dstpath) const isSymlink = fs.lstatSync(dstpath).isSymbolicLink() const dstContent = fs.readFileSync(dstpath, 'utf8') const dstDirContents = fs.readdirSync(dstDir) assert.strictEqual(isSymlink, true) assert.strictEqual(srcContent, dstContent) assert(dstDirContents.indexOf(dstBasename) >= 0) return done() } return fn(...args, callback) }) } function fileBroken (args, fn) { const srcpath = args[0] const dstpath = args[1] it(`should create broken symlink file using src ${srcpath} and dst ${dstpath}`, done => { const callback = err => { if (err) return done(err) const dstDir = path.dirname(dstpath) const dstBasename = path.basename(dstpath) const isSymlink = fs.lstatSync(dstpath).isSymbolicLink() const dstDirContents = fs.readdirSync(dstDir) assert.strictEqual(isSymlink, true) assert(dstDirContents.indexOf(dstBasename) >= 0) assert.throws(() => fs.readFileSync(dstpath, 'utf8'), Error) return done() } return fn(...args, callback) }) } function fileError (args, fn) { const srcpath = args[0] const dstpath = args[1] it(`should return error when creating symlink file using src ${srcpath} and dst ${dstpath}`, done => { const dstdirExistsBefore = fs.existsSync(path.dirname(dstpath)) const callback = err => { assert.strictEqual(err instanceof Error, true) // ensure that directories aren't created if there's an error const dstdirExistsAfter = fs.existsSync(path.dirname(dstpath)) assert.strictEqual(dstdirExistsBefore, dstdirExistsAfter) return done() } return fn(...args, callback) }) } function dirSuccess (args, fn) { const srcpath = args[0] const dstpath = args[1] it(`should create symlink dir using src ${srcpath} and dst ${dstpath}`, done => { const callback = err => { if (err) return done(err) const relative = symlinkPathsSync(srcpath, dstpath) const srcContents = fs.readdirSync(relative.toCwd) const dstDir = path.dirname(dstpath) const dstBasename = path.basename(dstpath) const isSymlink = fs.lstatSync(dstpath).isSymbolicLink() const dstContents = fs.readdirSync(dstpath) const dstDirContents = fs.readdirSync(dstDir) assert.strictEqual(isSymlink, true) assert.deepStrictEqual(srcContents, dstContents) assert(dstDirContents.indexOf(dstBasename) >= 0) return done() } return fn(...args, callback) }) } function dirBroken (args, fn) { const srcpath = args[0] const dstpath = args[1] it(`should create broken symlink dir using src ${srcpath} and dst ${dstpath}`, done => { const callback = err => { if (err) return done(err) const dstDir = path.dirname(dstpath) const dstBasename = path.basename(dstpath) const isSymlink = fs.lstatSync(dstpath).isSymbolicLink() const dstDirContents = fs.readdirSync(dstDir) assert.strictEqual(isSymlink, true) assert(dstDirContents.indexOf(dstBasename) >= 0) assert.throws(() => fs.readdirSync(dstpath), Error) return done() } return fn(...args, callback) }) } function dirError (args, fn) { const srcpath = args[0] const dstpath = args[1] it(`should return error when creating symlink dir using src ${srcpath} and dst ${dstpath}`, done => { const dstdirExistsBefore = fs.existsSync(path.dirname(dstpath)) const callback = err => { assert.strictEqual(err instanceof Error, true) // ensure that directories aren't created if there's an error const dstdirExistsAfter = fs.existsSync(path.dirname(dstpath)) assert.strictEqual(dstdirExistsBefore, dstdirExistsAfter) return done() } return fn(...args, callback) }) } function fileSuccessSync (args, fn) { const srcpath = args[0] const dstpath = args[1] it(`should create symlink file using src ${srcpath} and dst ${dstpath}`, () => { fn(...args) const relative = symlinkPathsSync(srcpath, dstpath) const srcContent = fs.readFileSync(relative.toCwd, 'utf8') const dstDir = path.dirname(dstpath) const dstBasename = path.basename(dstpath) const isSymlink = fs.lstatSync(dstpath).isSymbolicLink() const dstContent = fs.readFileSync(dstpath, 'utf8') const dstDirContents = fs.readdirSync(dstDir) assert.strictEqual(isSymlink, true) assert.strictEqual(srcContent, dstContent) assert(dstDirContents.indexOf(dstBasename) >= 0) }) } function fileBrokenSync (args, fn) { const srcpath = args[0] const dstpath = args[1] it(`should create broken symlink file using src ${srcpath} and dst ${dstpath}`, () => { fn(...args) const dstDir = path.dirname(dstpath) const dstBasename = path.basename(dstpath) const isSymlink = fs.lstatSync(dstpath).isSymbolicLink() const dstDirContents = fs.readdirSync(dstDir) assert.strictEqual(isSymlink, true) assert(dstDirContents.indexOf(dstBasename) >= 0) assert.throws(() => fs.readFileSync(dstpath, 'utf8'), Error) }) } function fileErrorSync (args, fn) { const srcpath = args[0] const dstpath = args[1] it(`should throw error using src ${srcpath} and dst ${dstpath}`, () => { const dstdirExistsBefore = fs.existsSync(path.dirname(dstpath)) let err = null try { fn(...args) } catch (e) { err = e } assert.strictEqual(err instanceof Error, true) const dstdirExistsAfter = fs.existsSync(path.dirname(dstpath)) assert.strictEqual(dstdirExistsBefore, dstdirExistsAfter) }) } function dirSuccessSync (args, fn) { const srcpath = args[0] const dstpath = args[1] it(`should create symlink dir using src ${srcpath} and dst ${dstpath}`, () => { fn(...args) const relative = symlinkPathsSync(srcpath, dstpath) const srcContents = fs.readdirSync(relative.toCwd) const dstDir = path.dirname(dstpath) const dstBasename = path.basename(dstpath) const isSymlink = fs.lstatSync(dstpath).isSymbolicLink() const dstContents = fs.readdirSync(dstpath) const dstDirContents = fs.readdirSync(dstDir) assert.strictEqual(isSymlink, true) assert.deepStrictEqual(srcContents, dstContents) assert(dstDirContents.indexOf(dstBasename) >= 0) }) } function dirBrokenSync (args, fn) { const srcpath = args[0] const dstpath = args[1] it(`should create broken symlink dir using src ${srcpath} and dst ${dstpath}`, () => { fn(...args) const dstDir = path.dirname(dstpath) const dstBasename = path.basename(dstpath) const isSymlink = fs.lstatSync(dstpath).isSymbolicLink() const dstDirContents = fs.readdirSync(dstDir) assert.strictEqual(isSymlink, true) assert(dstDirContents.indexOf(dstBasename) >= 0) assert.throws(() => fs.readdirSync(dstpath), Error) }) } function dirErrorSync (args, fn) { const srcpath = args[0] const dstpath = args[1] it(`should throw error when creating symlink dir using src ${srcpath} and dst ${dstpath}`, () => { const dstdirExistsBefore = fs.existsSync(path.dirname(dstpath)) let err = null try { fn(...args) } catch (e) { err = e } assert.strictEqual(err instanceof Error, true) const dstdirExistsAfter = fs.existsSync(path.dirname(dstpath)) assert.strictEqual(dstdirExistsBefore, dstdirExistsAfter) }) } describe('ensureSymlink()', () => { const fn = ensureSymlink tests.forEach(test => { const args = test[0] // const nativeBehavior = test[1] const newBehavior = test[2] if (newBehavior === 'file-success') fileSuccess(args, fn) if (newBehavior === 'file-broken') fileBroken(args, fn) if (newBehavior === 'file-error') fileError(args, fn) if (newBehavior === 'dir-success') dirSuccess(args, fn) if (newBehavior === 'dir-broken') dirBroken(args, fn) if (newBehavior === 'dir-error') dirError(args, fn) }) }) describe('ensureSymlink() promise support', () => { tests.filter(test => test[2] === 'file-success').forEach(test => { const args = test[0] const srcpath = args[0] const dstpath = args[1] it(`should create symlink file using src ${srcpath} and dst ${dstpath}`, () => { return ensureSymlink(srcpath, dstpath) .then(() => { const relative = symlinkPathsSync(srcpath, dstpath) const srcContent = fs.readFileSync(relative.toCwd, 'utf8') const dstDir = path.dirname(dstpath) const dstBasename = path.basename(dstpath) const isSymlink = fs.lstatSync(dstpath).isSymbolicLink() const dstContent = fs.readFileSync(dstpath, 'utf8') const dstDirContents = fs.readdirSync(dstDir) assert.strictEqual(isSymlink, true) assert.strictEqual(srcContent, dstContent) assert(dstDirContents.indexOf(dstBasename) >= 0) }) }) }) }) describe('ensureSymlinkSync()', () => { const fn = ensureSymlinkSync tests.forEach(test => { const args = test[0] // const nativeBehavior = test[1] const newBehavior = test[2] if (newBehavior === 'file-success') fileSuccessSync(args, fn) if (newBehavior === 'file-broken') fileBrokenSync(args, fn) if (newBehavior === 'file-error') fileErrorSync(args, fn) if (newBehavior === 'dir-success') dirSuccessSync(args, fn) if (newBehavior === 'dir-broken') dirBrokenSync(args, fn) if (newBehavior === 'dir-error') dirErrorSync(args, fn) }) }) // https://github.com/jprichardson/node-fs-extra/issues/1038 describe('ensureSymlink() with relative path called twice (issue #1038)', () => { it('should succeed when calling ensureSymlink twice with a relative path', async () => { const targetDir = path.join(TEST_DIR, 'target-1038') const linkDir = path.join(TEST_DIR, 'link-1038') const linkPath = path.join(linkDir, 'link') const relativeTarget = path.relative(linkDir, targetDir) // Create target directory with a file await fse.ensureDir(targetDir) fs.writeFileSync(path.join(targetDir, 'file.txt'), 'content') // First ensureSymlink call with relative path - should succeed await ensureSymlink(relativeTarget, linkPath, 'dir') assert.strictEqual(fs.lstatSync(linkPath).isSymbolicLink(), true) // Second ensureSymlink call with same relative path - should also succeed await ensureSymlink(relativeTarget, linkPath, 'dir') assert.strictEqual(fs.lstatSync(linkPath).isSymbolicLink(), true) // Verify the symlink still works const content = fs.readFileSync(path.join(linkPath, 'file.txt'), 'utf8') assert.strictEqual(content, 'content') }) it('should succeed when calling ensureSymlinkSync twice with a relative path', () => { const targetDir = path.join(TEST_DIR, 'target-1038-sync') const linkDir = path.join(TEST_DIR, 'link-1038-sync') const linkPath = path.join(linkDir, 'link') const relativeTarget = path.relative(linkDir, targetDir) // Create target directory with a file fse.ensureDirSync(targetDir) fs.writeFileSync(path.join(targetDir, 'file.txt'), 'content') // First ensureSymlinkSync call with relative path - should succeed ensureSymlinkSync(relativeTarget, linkPath, 'dir') assert.strictEqual(fs.lstatSync(linkPath).isSymbolicLink(), true) // Second ensureSymlinkSync call with same relative path - should also succeed ensureSymlinkSync(relativeTarget, linkPath, 'dir') assert.strictEqual(fs.lstatSync(linkPath).isSymbolicLink(), true) // Verify the symlink still works const content = fs.readFileSync(path.join(linkPath, 'file.txt'), 'utf8') assert.strictEqual(content, 'content') }) }) }) ================================================ FILE: lib/ensure/file.js ================================================ 'use strict' const u = require('universalify').fromPromise const path = require('path') const fs = require('../fs') const mkdir = require('../mkdirs') async function createFile (file) { let stats try { stats = await fs.stat(file) } catch { } if (stats && stats.isFile()) return const dir = path.dirname(file) let dirStats = null try { dirStats = await fs.stat(dir) } catch (err) { // if the directory doesn't exist, make it if (err.code === 'ENOENT') { await mkdir.mkdirs(dir) await fs.writeFile(file, '') return } else { throw err } } if (dirStats.isDirectory()) { await fs.writeFile(file, '') } else { // parent is not a directory // This is just to cause an internal ENOTDIR error to be thrown await fs.readdir(dir) } } function createFileSync (file) { let stats try { stats = fs.statSync(file) } catch { } if (stats && stats.isFile()) return const dir = path.dirname(file) try { if (!fs.statSync(dir).isDirectory()) { // parent is not a directory // This is just to cause an internal ENOTDIR error to be thrown fs.readdirSync(dir) } } catch (err) { // If the stat call above failed because the directory doesn't exist, create it if (err && err.code === 'ENOENT') mkdir.mkdirsSync(dir) else throw err } fs.writeFileSync(file, '') } module.exports = { createFile: u(createFile), createFileSync } ================================================ FILE: lib/ensure/index.js ================================================ 'use strict' const { createFile, createFileSync } = require('./file') const { createLink, createLinkSync } = require('./link') const { createSymlink, createSymlinkSync } = require('./symlink') module.exports = { // file createFile, createFileSync, ensureFile: createFile, ensureFileSync: createFileSync, // link createLink, createLinkSync, ensureLink: createLink, ensureLinkSync: createLinkSync, // symlink createSymlink, createSymlinkSync, ensureSymlink: createSymlink, ensureSymlinkSync: createSymlinkSync } ================================================ FILE: lib/ensure/link.js ================================================ 'use strict' const u = require('universalify').fromPromise const path = require('path') const fs = require('../fs') const mkdir = require('../mkdirs') const { pathExists } = require('../path-exists') const { areIdentical } = require('../util/stat') async function createLink (srcpath, dstpath) { let dstStat try { dstStat = await fs.lstat(dstpath) } catch { // ignore error } let srcStat try { srcStat = await fs.lstat(srcpath) } catch (err) { err.message = err.message.replace('lstat', 'ensureLink') throw err } if (dstStat && areIdentical(srcStat, dstStat)) return const dir = path.dirname(dstpath) const dirExists = await pathExists(dir) if (!dirExists) { await mkdir.mkdirs(dir) } await fs.link(srcpath, dstpath) } function createLinkSync (srcpath, dstpath) { let dstStat try { dstStat = fs.lstatSync(dstpath) } catch {} try { const srcStat = fs.lstatSync(srcpath) if (dstStat && areIdentical(srcStat, dstStat)) return } catch (err) { err.message = err.message.replace('lstat', 'ensureLink') throw err } const dir = path.dirname(dstpath) const dirExists = fs.existsSync(dir) if (dirExists) return fs.linkSync(srcpath, dstpath) mkdir.mkdirsSync(dir) return fs.linkSync(srcpath, dstpath) } module.exports = { createLink: u(createLink), createLinkSync } ================================================ FILE: lib/ensure/symlink-paths.js ================================================ 'use strict' const path = require('path') const fs = require('../fs') const { pathExists } = require('../path-exists') const u = require('universalify').fromPromise /** * Function that returns two types of paths, one relative to symlink, and one * relative to the current working directory. Checks if path is absolute or * relative. If the path is relative, this function checks if the path is * relative to symlink or relative to current working directory. This is an * initiative to find a smarter `srcpath` to supply when building symlinks. * This allows you to determine which path to use out of one of three possible * types of source paths. The first is an absolute path. This is detected by * `path.isAbsolute()`. When an absolute path is provided, it is checked to * see if it exists. If it does it's used, if not an error is returned * (callback)/ thrown (sync). The other two options for `srcpath` are a * relative url. By default Node's `fs.symlink` works by creating a symlink * using `dstpath` and expects the `srcpath` to be relative to the newly * created symlink. If you provide a `srcpath` that does not exist on the file * system it results in a broken symlink. To minimize this, the function * checks to see if the 'relative to symlink' source file exists, and if it * does it will use it. If it does not, it checks if there's a file that * exists that is relative to the current working directory, if does its used. * This preserves the expectations of the original fs.symlink spec and adds * the ability to pass in `relative to current working direcotry` paths. */ async function symlinkPaths (srcpath, dstpath) { if (path.isAbsolute(srcpath)) { try { await fs.lstat(srcpath) } catch (err) { err.message = err.message.replace('lstat', 'ensureSymlink') throw err } return { toCwd: srcpath, toDst: srcpath } } const dstdir = path.dirname(dstpath) const relativeToDst = path.join(dstdir, srcpath) const exists = await pathExists(relativeToDst) if (exists) { return { toCwd: relativeToDst, toDst: srcpath } } try { await fs.lstat(srcpath) } catch (err) { err.message = err.message.replace('lstat', 'ensureSymlink') throw err } return { toCwd: srcpath, toDst: path.relative(dstdir, srcpath) } } function symlinkPathsSync (srcpath, dstpath) { if (path.isAbsolute(srcpath)) { const exists = fs.existsSync(srcpath) if (!exists) throw new Error('absolute srcpath does not exist') return { toCwd: srcpath, toDst: srcpath } } const dstdir = path.dirname(dstpath) const relativeToDst = path.join(dstdir, srcpath) const exists = fs.existsSync(relativeToDst) if (exists) { return { toCwd: relativeToDst, toDst: srcpath } } const srcExists = fs.existsSync(srcpath) if (!srcExists) throw new Error('relative srcpath does not exist') return { toCwd: srcpath, toDst: path.relative(dstdir, srcpath) } } module.exports = { symlinkPaths: u(symlinkPaths), symlinkPathsSync } ================================================ FILE: lib/ensure/symlink-type.js ================================================ 'use strict' const fs = require('../fs') const u = require('universalify').fromPromise async function symlinkType (srcpath, type) { if (type) return type let stats try { stats = await fs.lstat(srcpath) } catch { return 'file' } return (stats && stats.isDirectory()) ? 'dir' : 'file' } function symlinkTypeSync (srcpath, type) { if (type) return type let stats try { stats = fs.lstatSync(srcpath) } catch { return 'file' } return (stats && stats.isDirectory()) ? 'dir' : 'file' } module.exports = { symlinkType: u(symlinkType), symlinkTypeSync } ================================================ FILE: lib/ensure/symlink.js ================================================ 'use strict' const u = require('universalify').fromPromise const path = require('path') const fs = require('../fs') const { mkdirs, mkdirsSync } = require('../mkdirs') const { symlinkPaths, symlinkPathsSync } = require('./symlink-paths') const { symlinkType, symlinkTypeSync } = require('./symlink-type') const { pathExists } = require('../path-exists') const { areIdentical } = require('../util/stat') async function createSymlink (srcpath, dstpath, type) { let stats try { stats = await fs.lstat(dstpath) } catch { } if (stats && stats.isSymbolicLink()) { // When srcpath is relative, resolve it relative to dstpath's directory // (standard symlink behavior) or fall back to cwd if that doesn't exist let srcStat if (path.isAbsolute(srcpath)) { srcStat = await fs.stat(srcpath) } else { const dstdir = path.dirname(dstpath) const relativeToDst = path.join(dstdir, srcpath) try { srcStat = await fs.stat(relativeToDst) } catch { srcStat = await fs.stat(srcpath) } } const dstStat = await fs.stat(dstpath) if (areIdentical(srcStat, dstStat)) return } const relative = await symlinkPaths(srcpath, dstpath) srcpath = relative.toDst const toType = await symlinkType(relative.toCwd, type) const dir = path.dirname(dstpath) if (!(await pathExists(dir))) { await mkdirs(dir) } return fs.symlink(srcpath, dstpath, toType) } function createSymlinkSync (srcpath, dstpath, type) { let stats try { stats = fs.lstatSync(dstpath) } catch { } if (stats && stats.isSymbolicLink()) { // When srcpath is relative, resolve it relative to dstpath's directory // (standard symlink behavior) or fall back to cwd if that doesn't exist let srcStat if (path.isAbsolute(srcpath)) { srcStat = fs.statSync(srcpath) } else { const dstdir = path.dirname(dstpath) const relativeToDst = path.join(dstdir, srcpath) try { srcStat = fs.statSync(relativeToDst) } catch { srcStat = fs.statSync(srcpath) } } const dstStat = fs.statSync(dstpath) if (areIdentical(srcStat, dstStat)) return } const relative = symlinkPathsSync(srcpath, dstpath) srcpath = relative.toDst type = symlinkTypeSync(relative.toCwd, type) const dir = path.dirname(dstpath) const exists = fs.existsSync(dir) if (exists) return fs.symlinkSync(srcpath, dstpath, type) mkdirsSync(dir) return fs.symlinkSync(srcpath, dstpath, type) } module.exports = { createSymlink: u(createSymlink), createSymlinkSync } ================================================ FILE: lib/esm.mjs ================================================ import _copy from './copy/index.js' import _empty from './empty/index.js' import _ensure from './ensure/index.js' import _json from './json/index.js' import _mkdirs from './mkdirs/index.js' import _move from './move/index.js' import _outputFile from './output-file/index.js' import _pathExists from './path-exists/index.js' import _remove from './remove/index.js' // NOTE: Only exports fs-extra's functions; fs functions must be imported from "node:fs" or "node:fs/promises" export const copy = _copy.copy export const copySync = _copy.copySync export const emptyDirSync = _empty.emptyDirSync export const emptydirSync = _empty.emptydirSync export const emptyDir = _empty.emptyDir export const emptydir = _empty.emptydir export const createFile = _ensure.createFile export const createFileSync = _ensure.createFileSync export const ensureFile = _ensure.ensureFile export const ensureFileSync = _ensure.ensureFileSync export const createLink = _ensure.createLink export const createLinkSync = _ensure.createLinkSync export const ensureLink = _ensure.ensureLink export const ensureLinkSync = _ensure.ensureLinkSync export const createSymlink = _ensure.createSymlink export const createSymlinkSync = _ensure.createSymlinkSync export const ensureSymlink = _ensure.ensureSymlink export const ensureSymlinkSync = _ensure.ensureSymlinkSync export const readJson = _json.readJson export const readJSON = _json.readJSON export const readJsonSync = _json.readJsonSync export const readJSONSync = _json.readJSONSync export const writeJson = _json.writeJson export const writeJSON = _json.writeJSON export const writeJsonSync = _json.writeJsonSync export const writeJSONSync = _json.writeJSONSync export const outputJson = _json.outputJson export const outputJSON = _json.outputJSON export const outputJsonSync = _json.outputJsonSync export const outputJSONSync = _json.outputJSONSync export const mkdirs = _mkdirs.mkdirs export const mkdirsSync = _mkdirs.mkdirsSync export const mkdirp = _mkdirs.mkdirp export const mkdirpSync = _mkdirs.mkdirpSync export const ensureDir = _mkdirs.ensureDir export const ensureDirSync = _mkdirs.ensureDirSync export const move = _move.move export const moveSync = _move.moveSync export const outputFile = _outputFile.outputFile export const outputFileSync = _outputFile.outputFileSync export const pathExists = _pathExists.pathExists export const pathExistsSync = _pathExists.pathExistsSync export const remove = _remove.remove export const removeSync = _remove.removeSync export default { ..._copy, ..._empty, ..._ensure, ..._json, ..._mkdirs, ..._move, ..._outputFile, ..._pathExists, ..._remove } ================================================ FILE: lib/fs/__tests__/copyFile.test.js ================================================ 'use strict' const os = require('os') const fse = require('../..') const path = require('path') const assert = require('assert') /* eslint-env mocha */ describe('fs.copyFile', () => { let TEST_DIR beforeEach(done => { TEST_DIR = path.join(os.tmpdir(), 'fs-extra', 'fs-copyfile') fse.emptyDir(TEST_DIR, done) }) afterEach(done => fse.remove(TEST_DIR, done)) it('supports promises', () => { const src = path.join(TEST_DIR, 'init.txt') const dest = path.join(TEST_DIR, 'copy.txt') fse.writeFileSync(src, 'hello') return fse.copyFile(src, dest).then(() => { const data = fse.readFileSync(dest, 'utf8') assert.strictEqual(data, 'hello') }) }) }) ================================================ FILE: lib/fs/__tests__/fs-integration.test.js ================================================ 'use strict' const os = require('os') const fs = require('fs') const fse = require('../..') const path = require('path') const assert = require('assert') /* global afterEach, beforeEach, describe, it */ describe('native fs', () => { let TEST_DIR beforeEach(done => { TEST_DIR = path.join(os.tmpdir(), 'fs-extra', 'native-fs') fse.emptyDir(TEST_DIR, done) }) afterEach(done => fse.remove(TEST_DIR, done)) it('should use native fs methods', () => { const file = path.join(TEST_DIR, 'write.txt') fse.writeFileSync(file, 'hello') const data = fse.readFileSync(file, 'utf8') assert.strictEqual(data, 'hello') }) it('should have native fs constants', () => { assert.strictEqual(fse.constants.F_OK, fs.constants.F_OK) }) }) ================================================ FILE: lib/fs/__tests__/multi-param.test.js ================================================ 'use strict' /* eslint-env mocha */ const assert = require('assert') const path = require('path') const crypto = require('crypto') const os = require('os') const fs = require('../..') const SIZE = 1000 describe('fs.read()', () => { let TEST_FILE let TEST_DATA let TEST_FD beforeEach(() => { TEST_FILE = path.join(os.tmpdir(), 'fs-extra', 'read-test-file') TEST_DATA = crypto.randomBytes(SIZE) fs.writeFileSync(TEST_FILE, TEST_DATA) TEST_FD = fs.openSync(TEST_FILE, 'r') }) afterEach(() => { return fs.close(TEST_FD) .then(() => fs.remove(TEST_FILE)) }) describe('with promises', () => { it('returns an object', () => { return fs.read(TEST_FD, Buffer.alloc(SIZE), 0, SIZE, 0) .then(results => { const bytesRead = results.bytesRead const buffer = results.buffer assert.strictEqual(bytesRead, SIZE, 'bytesRead is correct') assert(buffer.equals(TEST_DATA), 'data is correct') }) }) it('returns an object when position is not set', () => { return fs.read(TEST_FD, Buffer.alloc(SIZE), 0, SIZE) .then(results => { const bytesRead = results.bytesRead const buffer = results.buffer assert.strictEqual(bytesRead, SIZE, 'bytesRead is correct') assert(buffer.equals(TEST_DATA), 'data is correct') }) }) }) describe('with callbacks', () => { it('works', done => { fs.read(TEST_FD, Buffer.alloc(SIZE), 0, SIZE, 0, (err, bytesRead, buffer) => { assert.ifError(err) assert.strictEqual(bytesRead, SIZE, 'bytesRead is correct') assert(buffer.equals(TEST_DATA), 'data is correct') done() }) }) it('works when position is null', done => { fs.read(TEST_FD, Buffer.alloc(SIZE), 0, SIZE, null, (err, bytesRead, buffer) => { assert.ifError(err) assert.strictEqual(bytesRead, SIZE, 'bytesRead is correct') assert(buffer.equals(TEST_DATA), 'data is correct') done() }) }) }) }) describe('fs.write()', () => { let TEST_FILE let TEST_DATA let TEST_FD beforeEach(() => { TEST_FILE = path.join(os.tmpdir(), 'fs-extra', 'write-test-file') TEST_DATA = crypto.randomBytes(SIZE) fs.ensureDirSync(path.dirname(TEST_FILE)) TEST_FD = fs.openSync(TEST_FILE, 'w') }) afterEach(() => { return fs.close(TEST_FD) .then(() => fs.remove(TEST_FILE)) }) describe('with promises', () => { it('returns an object', () => { return fs.write(TEST_FD, TEST_DATA, 0, SIZE, 0) .then(results => { const bytesWritten = results.bytesWritten const buffer = results.buffer assert.strictEqual(bytesWritten, SIZE, 'bytesWritten is correct') assert(buffer.equals(TEST_DATA), 'data is correct') }) }) it('returns an object when minimal arguments are passed', () => { return fs.write(TEST_FD, TEST_DATA) .then(results => { const bytesWritten = results.bytesWritten const buffer = results.buffer assert.strictEqual(bytesWritten, SIZE, 'bytesWritten is correct') assert(buffer.equals(TEST_DATA), 'data is correct') }) }) it('returns an object when writing a string', () => { const message = 'Hello World!' return fs.write(TEST_FD, message) .then(results => { const bytesWritten = results.bytesWritten const buffer = results.buffer assert.strictEqual(bytesWritten, message.length, 'bytesWritten is correct') assert.strictEqual(buffer, message, 'data is correct') }) }) }) describe('with callbacks', () => { it('works', done => { fs.write(TEST_FD, TEST_DATA, 0, SIZE, 0, (err, bytesWritten, buffer) => { assert.ifError(err) assert.strictEqual(bytesWritten, SIZE, 'bytesWritten is correct') assert(buffer.equals(TEST_DATA), 'data is correct') done() }) }) it('works when minimal arguments are passed', done => { fs.write(TEST_FD, TEST_DATA, (err, bytesWritten, buffer) => { assert.ifError(err) assert.strictEqual(bytesWritten, SIZE, 'bytesWritten is correct') assert(buffer.equals(TEST_DATA), 'data is correct') done() }) }) it('works when writing a string', done => { const message = 'Hello World!' return fs.write(TEST_FD, message, (err, bytesWritten, buffer) => { assert.ifError(err) assert.strictEqual(bytesWritten, message.length, 'bytesWritten is correct') assert.strictEqual(buffer, message, 'data is correct') done() }) }) }) }) describe('fs.readv()', () => { let TEST_FILE let TEST_DATA let TEST_FD beforeEach(() => { TEST_FILE = path.join(os.tmpdir(), 'fs-extra', 'readv-test-file') TEST_DATA = crypto.randomBytes(SIZE) fs.writeFileSync(TEST_FILE, TEST_DATA) TEST_FD = fs.openSync(TEST_FILE, 'r') }) afterEach(() => { return fs.close(TEST_FD) .then(() => fs.remove(TEST_FILE)) }) describe('with promises', () => { it('returns an object', () => { const bufferArray = [Buffer.alloc(SIZE / 2), Buffer.alloc(SIZE / 2)] return fs.readv(TEST_FD, bufferArray, 0) .then(({ bytesRead, buffers }) => { assert.strictEqual(bytesRead, SIZE, 'bytesRead is correct') assert.deepStrictEqual(buffers, bufferArray, 'returned data matches mutated input param') assert.deepStrictEqual(Buffer.concat(buffers), TEST_DATA, 'data is correct') }) }) it('returns an object when minimal arguments are passed', () => { const bufferArray = [Buffer.alloc(SIZE / 2), Buffer.alloc(SIZE / 2)] return fs.readv(TEST_FD, bufferArray) .then(({ bytesRead, buffers }) => { assert.strictEqual(bytesRead, SIZE, 'bytesRead is correct') assert.deepStrictEqual(buffers, bufferArray, 'returned data matches mutated input param') assert.deepStrictEqual(Buffer.concat(buffers), TEST_DATA, 'data is correct') }) }) }) describe('with callbacks', () => { it('works', done => { const bufferArray = [Buffer.alloc(SIZE / 2), Buffer.alloc(SIZE / 2)] fs.readv(TEST_FD, bufferArray, 0, (err, bytesRead, buffers) => { assert.ifError(err) assert.strictEqual(bytesRead, SIZE, 'bytesRead is correct') assert.deepStrictEqual(buffers, bufferArray, 'returned data matches mutated input param') assert.deepStrictEqual(Buffer.concat(buffers), TEST_DATA, 'data is correct') done() }) }) it('works when minimal arguments are passed', done => { const bufferArray = [Buffer.alloc(SIZE / 2), Buffer.alloc(SIZE / 2)] fs.readv(TEST_FD, bufferArray, (err, bytesRead, buffers) => { assert.ifError(err) assert.strictEqual(bytesRead, SIZE, 'bytesRead is correct') assert.deepStrictEqual(buffers, bufferArray, 'returned data matches mutated input param') assert.deepStrictEqual(Buffer.concat(buffers), TEST_DATA, 'data is correct') done() }) }) }) }) describe('fs.writev()', () => { let TEST_FILE let TEST_DATA let TEST_FD beforeEach(() => { TEST_FILE = path.join(os.tmpdir(), 'fs-extra', 'writev-test-file') TEST_DATA = [crypto.randomBytes(SIZE / 2), crypto.randomBytes(SIZE / 2)] fs.ensureDirSync(path.dirname(TEST_FILE)) TEST_FD = fs.openSync(TEST_FILE, 'w') }) afterEach(() => { return fs.close(TEST_FD) .then(() => fs.remove(TEST_FILE)) }) describe('with promises', () => { it('returns an object', () => { return fs.writev(TEST_FD, TEST_DATA, 0) .then(({ bytesWritten, buffers }) => { assert.strictEqual(bytesWritten, SIZE, 'bytesWritten is correct') assert.deepStrictEqual(buffers, TEST_DATA, 'data is correct') }) }) it('returns an object when minimal arguments are passed', () => { return fs.writev(TEST_FD, TEST_DATA) .then(({ bytesWritten, buffers }) => { assert.strictEqual(bytesWritten, SIZE, 'bytesWritten is correct') assert.deepStrictEqual(buffers, TEST_DATA, 'data is correct') }) }) }) describe('with callbacks', () => { it('works', done => { fs.writev(TEST_FD, TEST_DATA, 0, (err, bytesWritten, buffers) => { assert.ifError(err) assert.strictEqual(bytesWritten, SIZE, 'bytesWritten is correct') assert.deepStrictEqual(buffers, TEST_DATA, 'data is correct') done() }) }) it('works when minimal arguments are passed', done => { fs.writev(TEST_FD, TEST_DATA, (err, bytesWritten, buffers) => { assert.ifError(err) assert.strictEqual(bytesWritten, SIZE, 'bytesWritten is correct') assert.deepStrictEqual(buffers, TEST_DATA, 'data is correct') done() }) }) }) }) ================================================ FILE: lib/fs/__tests__/mz.test.js ================================================ 'use strict' // This is adapted from https://github.com/normalize/mz // Copyright (c) 2014-2016 Jonathan Ong me@jongleberry.com and Contributors /* eslint-env mocha */ const assert = require('assert') const fs = require('../..') describe('fs', () => { it('.stat()', done => { fs.stat(__filename).then(stats => { assert.strictEqual(typeof stats.size, 'number') done() }).catch(done) }) it('.statSync()', () => { const stats = fs.statSync(__filename) assert.strictEqual(typeof stats.size, 'number') }) it('.exists()', done => { fs.exists(__filename).then(exists => { assert(exists) done() }).catch(done) }) it('.existsSync()', () => { const exists = fs.existsSync(__filename) assert(exists) }) describe('callback support', () => { it('.stat()', done => { fs.stat(__filename, (err, stats) => { assert(!err) assert.strictEqual(typeof stats.size, 'number') done() }) }) // This test is different from mz/fs, since we are a drop-in replacement for native fs it('.exists()', done => { fs.exists(__filename, exists => { assert(exists) done() }) }) }) }) ================================================ FILE: lib/fs/__tests__/realpath.test.js ================================================ 'use strict' const fs = require('fs') const path = require('path') const assert = require('assert') /* eslint-env mocha */ describe('realpath.native does not exist', () => { let warning const warningListener = error => { if (error.name === 'Warning') { if (error.code.startsWith('fs-extra-WARN0003')) { warning = error } } } const realpathNativeBackup = fs.realpath.native const clearFseCache = () => { const fsePath = path.dirname(require.resolve('../..')) for (const entry in require.cache) { if (entry.startsWith(fsePath)) { delete require.cache[entry] } } } before(() => { process.on('warning', warningListener) // clear existing require.cache clearFseCache() // simulate fs monkey-patch delete fs.realpath.native }) after(() => { process.off('warning', warningListener) // clear stubbed require.cache clearFseCache() // reinstate fs.realpath.native fs.realpath.native = realpathNativeBackup }) it('fse should not export realpath.native', done => { const fse = require('../..') // next event loop to allow event emitter/listener to happen setImmediate(() => { assert(warning, 'fs-extra-WARN0003 should be emitted') done() }) assert(!fse.realpath.native) }) }) describe('realpath.native', () => { const fse = require('../..') it('works with callbacks', () => { fse.realpath.native(__dirname, (err, path) => { assert.ifError(err) assert.strictEqual(path, __dirname) }) }) it('works with promises', (done) => { fse.realpath.native(__dirname) .then(path => { assert.strictEqual(path, __dirname) done() }) .catch(done) }) it('works with sync version', () => { const path = fse.realpathSync.native(__dirname) assert.strictEqual(path, __dirname) }) }) ================================================ FILE: lib/fs/__tests__/rm.test.js ================================================ 'use strict' const fse = require('../..') const os = require('os') const path = require('path') const assert = require('assert') /* eslint-env mocha */ describe('fs.rm', () => { let TEST_FILE beforeEach(done => { TEST_FILE = path.join(os.tmpdir(), 'fs-extra', 'fs-rm') fse.remove(TEST_FILE, done) }) afterEach(done => fse.remove(TEST_FILE, done)) it('supports promises', () => { fse.writeFileSync(TEST_FILE, 'hello') return fse.rm(TEST_FILE).then(() => { assert(!fse.pathExistsSync(TEST_FILE)) }) }) }) ================================================ FILE: lib/fs/index.js ================================================ 'use strict' // This is adapted from https://github.com/normalize/mz // Copyright (c) 2014-2016 Jonathan Ong me@jongleberry.com and Contributors const u = require('universalify').fromCallback const fs = require('graceful-fs') const api = [ 'access', 'appendFile', 'chmod', 'chown', 'close', 'copyFile', 'cp', 'fchmod', 'fchown', 'fdatasync', 'fstat', 'fsync', 'ftruncate', 'futimes', 'glob', 'lchmod', 'lchown', 'lutimes', 'link', 'lstat', 'mkdir', 'mkdtemp', 'open', 'opendir', 'readdir', 'readFile', 'readlink', 'realpath', 'rename', 'rm', 'rmdir', 'stat', 'statfs', 'symlink', 'truncate', 'unlink', 'utimes', 'writeFile' ].filter(key => { // Some commands are not available on some systems. Ex: // fs.cp was added in Node.js v16.7.0 // fs.statfs was added in Node v19.6.0, v18.15.0 // fs.glob was added in Node.js v22.0.0 // fs.lchown is not available on at least some Linux return typeof fs[key] === 'function' }) // Export cloned fs: Object.assign(exports, fs) // Universalify async methods: api.forEach(method => { exports[method] = u(fs[method]) }) // We differ from mz/fs in that we still ship the old, broken, fs.exists() // since we are a drop-in replacement for the native module exports.exists = function (filename, callback) { if (typeof callback === 'function') { return fs.exists(filename, callback) } return new Promise(resolve => { return fs.exists(filename, resolve) }) } // fs.read(), fs.write(), fs.readv(), & fs.writev() need special treatment due to multiple callback args exports.read = function (fd, buffer, offset, length, position, callback) { if (typeof callback === 'function') { return fs.read(fd, buffer, offset, length, position, callback) } return new Promise((resolve, reject) => { fs.read(fd, buffer, offset, length, position, (err, bytesRead, buffer) => { if (err) return reject(err) resolve({ bytesRead, buffer }) }) }) } // Function signature can be // fs.write(fd, buffer[, offset[, length[, position]]], callback) // OR // fs.write(fd, string[, position[, encoding]], callback) // We need to handle both cases, so we use ...args exports.write = function (fd, buffer, ...args) { if (typeof args[args.length - 1] === 'function') { return fs.write(fd, buffer, ...args) } return new Promise((resolve, reject) => { fs.write(fd, buffer, ...args, (err, bytesWritten, buffer) => { if (err) return reject(err) resolve({ bytesWritten, buffer }) }) }) } // Function signature is // s.readv(fd, buffers[, position], callback) // We need to handle the optional arg, so we use ...args exports.readv = function (fd, buffers, ...args) { if (typeof args[args.length - 1] === 'function') { return fs.readv(fd, buffers, ...args) } return new Promise((resolve, reject) => { fs.readv(fd, buffers, ...args, (err, bytesRead, buffers) => { if (err) return reject(err) resolve({ bytesRead, buffers }) }) }) } // Function signature is // s.writev(fd, buffers[, position], callback) // We need to handle the optional arg, so we use ...args exports.writev = function (fd, buffers, ...args) { if (typeof args[args.length - 1] === 'function') { return fs.writev(fd, buffers, ...args) } return new Promise((resolve, reject) => { fs.writev(fd, buffers, ...args, (err, bytesWritten, buffers) => { if (err) return reject(err) resolve({ bytesWritten, buffers }) }) }) } // fs.realpath.native sometimes not available if fs is monkey-patched if (typeof fs.realpath.native === 'function') { exports.realpath.native = u(fs.realpath.native) } else { process.emitWarning( 'fs.realpath.native is not a function. Is fs being monkey-patched?', 'Warning', 'fs-extra-WARN0003' ) } ================================================ FILE: lib/index.js ================================================ 'use strict' module.exports = { // Export promiseified graceful-fs: ...require('./fs'), // Export extra methods: ...require('./copy'), ...require('./empty'), ...require('./ensure'), ...require('./json'), ...require('./mkdirs'), ...require('./move'), ...require('./output-file'), ...require('./path-exists'), ...require('./remove') } ================================================ FILE: lib/json/__tests__/jsonfile-integration.test.js ================================================ 'use strict' const fs = require('fs') const os = require('os') const fse = require('../..') const path = require('path') const assert = require('assert') /* global afterEach, beforeEach, describe, it */ describe('jsonfile-integration', () => { let TEST_DIR beforeEach(done => { TEST_DIR = path.join(os.tmpdir(), 'fs-extra', 'json') fse.emptyDir(TEST_DIR, done) }) afterEach(done => fse.remove(TEST_DIR, done)) describe('+ writeJsonSync / spaces', () => { it('should read a file and parse the json', () => { const obj1 = { firstName: 'JP', lastName: 'Richardson' } const file = path.join(TEST_DIR, 'file.json') fse.writeJsonSync(file, obj1) const data = fs.readFileSync(file, 'utf8') assert.strictEqual(data, JSON.stringify(obj1) + '\n') }) }) describe('+ writeJsonSync / EOL', () => { it('should read a file and parse the json', () => { const obj1 = { firstName: 'JP', lastName: 'Richardson' } const file = path.join(TEST_DIR, 'file.json') fse.writeJsonSync(file, obj1, { spaces: 2, EOL: '\r\n' }) const data = fs.readFileSync(file, 'utf8') assert.strictEqual( data, JSON.stringify(obj1, null, 2).replace(/\n/g, '\r\n') + '\r\n' ) }) }) }) ================================================ FILE: lib/json/__tests__/output-json-sync.test.js ================================================ 'use strict' const fs = require('fs') const os = require('os') const fse = require('../..') const path = require('path') const assert = require('assert') /* global beforeEach, describe, it */ describe('json', () => { let TEST_DIR beforeEach(done => { TEST_DIR = path.join(os.tmpdir(), 'fs-extra-output-json-sync') fse.emptyDir(TEST_DIR, done) }) describe('+ outputJsonSync(file, data)', () => { it('should write the file regardless of whether the directory exists or not', () => { const file = path.join(TEST_DIR, 'this-dir', 'does-not', 'exist', 'file.json') assert(!fs.existsSync(file)) const data = { name: 'JP' } fse.outputJsonSync(file, data) assert(fs.existsSync(file)) const newData = JSON.parse(fs.readFileSync(file, 'utf8')) assert.strictEqual(data.name, newData.name) }) describe('> when an option is passed, like JSON replacer', () => { it('should pass the option along to jsonfile module', () => { const file = path.join(TEST_DIR, 'this-dir', 'does-not', 'exist', 'really', 'file.json') assert(!fs.existsSync(file)) const replacer = (k, v) => v === 'JP' ? 'Jon Paul' : v const data = { name: 'JP' } fse.outputJsonSync(file, data, { replacer }) const newData = JSON.parse(fs.readFileSync(file, 'utf8')) assert.strictEqual(newData.name, 'Jon Paul') }) }) }) }) ================================================ FILE: lib/json/__tests__/output-json.test.js ================================================ 'use strict' const fs = require('fs') const os = require('os') const fse = require('../..') const path = require('path') const assert = require('assert') /* global beforeEach, describe, it */ describe('json', () => { let TEST_DIR beforeEach(done => { TEST_DIR = path.join(os.tmpdir(), 'fs-extra-output-json') fse.emptyDir(TEST_DIR, done) }) describe('+ outputJson(file, data)', () => { it('should write the file regardless of whether the directory exists or not', done => { const file = path.join(TEST_DIR, 'this-dir', 'prob-does-not', 'exist', 'file.json') assert(!fs.existsSync(file)) const data = { name: 'JP' } fse.outputJson(file, data, err => { if (err) return done(err) assert(fs.existsSync(file)) const newData = JSON.parse(fs.readFileSync(file, 'utf8')) assert.strictEqual(data.name, newData.name) done() }) }) it('should be mutation-proof', async () => { const dir = path.join(TEST_DIR, 'this-dir', 'certanly-does-not', 'exist') const file = path.join(dir, 'file.json') assert(!fs.existsSync(dir), 'directory cannot exist') const name = 'JP' const data = { name } const promise = fse.outputJson(file, data) // Mutate data right after call data.name = 'Ryan' // now await for the call to finish await promise assert(fs.existsSync(file)) const newData = JSON.parse(fs.readFileSync(file, 'utf8')) // mutation did not change data assert.strictEqual(newData.name, name) }) it('should support Promises', () => { const file = path.join(TEST_DIR, 'this-dir', 'prob-does-not', 'exist', 'file.json') assert(!fs.existsSync(file)) const data = { name: 'JP' } return fse.outputJson(file, data) }) describe('> when an option is passed, like JSON replacer', () => { it('should pass the option along to jsonfile module', done => { const file = path.join(TEST_DIR, 'this-dir', 'does-not', 'exist', 'really', 'file.json') assert(!fs.existsSync(file)) const replacer = (k, v) => v === 'JP' ? 'Jon Paul' : v const data = { name: 'JP' } fse.outputJson(file, data, { replacer }, err => { assert.ifError(err) const newData = JSON.parse(fs.readFileSync(file, 'utf8')) assert.strictEqual(newData.name, 'Jon Paul') done() }) }) }) }) }) ================================================ FILE: lib/json/__tests__/promise-support.test.js ================================================ 'use strict' const fs = require('fs') const os = require('os') const fse = require('../..') const path = require('path') const assert = require('assert') /* global afterEach, beforeEach, describe, it */ describe('json promise support', () => { let TEST_DIR beforeEach(done => { TEST_DIR = path.join(os.tmpdir(), 'fs-extra', 'json') fse.emptyDir(TEST_DIR, done) }) afterEach(done => fse.remove(TEST_DIR, done)) ;['writeJson', 'writeJSON'].forEach(method => { describe(method, () => { it('should support promises', () => { const obj1 = { firstName: 'JP', lastName: 'Richardson' } const file = path.join(TEST_DIR, 'promise.json') return fse[method](file, obj1) .then(() => { const data = fs.readFileSync(file, 'utf8') assert.strictEqual(data, JSON.stringify(obj1) + '\n') }) }) }) }) }) ================================================ FILE: lib/json/__tests__/read.test.js ================================================ 'use strict' const fs = require('fs') const os = require('os') const fse = require('../..') const path = require('path') const assert = require('assert') /* global afterEach, beforeEach, describe, it */ describe('read', () => { let TEST_DIR beforeEach(done => { TEST_DIR = path.join(os.tmpdir(), 'fs-extra', 'read-json') fse.emptyDir(TEST_DIR, done) }) afterEach(done => fse.remove(TEST_DIR, done)) describe('+ readJSON', () => { it('should read a file and parse the json', done => { const obj1 = { firstName: 'JP', lastName: 'Richardson' } const file = path.join(TEST_DIR, 'file.json') fs.writeFileSync(file, JSON.stringify(obj1)) fse.readJSON(file, (err, obj2) => { assert.ifError(err) assert.strictEqual(obj1.firstName, obj2.firstName) assert.strictEqual(obj1.lastName, obj2.lastName) done() }) }) it('should error if it cant parse the json', done => { const file = path.join(TEST_DIR, 'file2.json') fs.writeFileSync(file, '%asdfasdff444') fse.readJSON(file, (err, obj) => { assert(err) assert(!obj) done() }) }) }) }) ================================================ FILE: lib/json/index.js ================================================ 'use strict' const u = require('universalify').fromPromise const jsonFile = require('./jsonfile') jsonFile.outputJson = u(require('./output-json')) jsonFile.outputJsonSync = require('./output-json-sync') // aliases jsonFile.outputJSON = jsonFile.outputJson jsonFile.outputJSONSync = jsonFile.outputJsonSync jsonFile.writeJSON = jsonFile.writeJson jsonFile.writeJSONSync = jsonFile.writeJsonSync jsonFile.readJSON = jsonFile.readJson jsonFile.readJSONSync = jsonFile.readJsonSync module.exports = jsonFile ================================================ FILE: lib/json/jsonfile.js ================================================ 'use strict' const jsonFile = require('jsonfile') module.exports = { // jsonfile exports readJson: jsonFile.readFile, readJsonSync: jsonFile.readFileSync, writeJson: jsonFile.writeFile, writeJsonSync: jsonFile.writeFileSync } ================================================ FILE: lib/json/output-json-sync.js ================================================ 'use strict' const { stringify } = require('jsonfile/utils') const { outputFileSync } = require('../output-file') function outputJsonSync (file, data, options) { const str = stringify(data, options) outputFileSync(file, str, options) } module.exports = outputJsonSync ================================================ FILE: lib/json/output-json.js ================================================ 'use strict' const { stringify } = require('jsonfile/utils') const { outputFile } = require('../output-file') async function outputJson (file, data, options = {}) { const str = stringify(data, options) await outputFile(file, str, options) } module.exports = outputJson ================================================ FILE: lib/mkdirs/__tests__/chmod.test.js ================================================ 'use strict' const fs = require('fs') const os = require('os') const fse = require('../../') const path = require('path') const assert = require('assert') /* global afterEach, beforeEach, describe, it */ describe('mkdirp / chmod', () => { let TEST_DIR let TEST_SUBDIR beforeEach(done => { const ps = [] for (let i = 0; i < 15; i++) { const dir = Math.floor(Math.random() * Math.pow(16, 4)).toString(16) ps.push(dir) } TEST_SUBDIR = ps.join(path.sep) TEST_DIR = path.join(os.tmpdir(), 'fs-extra', 'mkdirp-chmod') TEST_SUBDIR = path.join(TEST_DIR, TEST_SUBDIR) fse.emptyDir(TEST_DIR, done) }) afterEach(done => fse.remove(TEST_DIR, done)) it('chmod-pre', done => { const mode = 0o744 fse.mkdirp(TEST_SUBDIR, mode, err => { assert.ifError(err, 'should not error') fs.stat(TEST_SUBDIR, (err, stat) => { assert.ifError(err, 'should exist') assert.ok(stat && stat.isDirectory(), 'should be directory') if (os.platform().indexOf('win') === 0) { assert.strictEqual(stat && stat.mode & 0o777, 0o666, 'windows shit') } else { assert.strictEqual(stat && stat.mode & 0o777, mode, 'should be 0744') } done() }) }) }) it('chmod', done => { const mode = 0o755 fse.mkdirp(TEST_SUBDIR, mode, err => { assert.ifError(err, 'should not error') fs.stat(TEST_SUBDIR, (err, stat) => { assert.ifError(err, 'should exist') assert.ok(stat && stat.isDirectory(), 'should be directory') done() }) }) }) }) ================================================ FILE: lib/mkdirs/__tests__/clobber.test.js ================================================ 'use strict' const fs = require('fs') const os = require('os') const fse = require('../..') const path = require('path') const assert = require('assert') /* global before, describe, it */ describe('mkdirp / clobber', () => { let TEST_DIR let file before(done => { TEST_DIR = path.join(os.tmpdir(), 'fs-extra', 'mkdirp-clobber') fse.emptyDir(TEST_DIR, err => { assert.ifError(err) const ps = [TEST_DIR] for (let i = 0; i < 15; i++) { const dir = Math.floor(Math.random() * Math.pow(16, 4)).toString(16) ps.push(dir) } file = ps.join(path.sep) // a file in the way const itw = ps.slice(0, 2).join(path.sep) fs.writeFileSync(itw, 'I AM IN THE WAY, THE TRUTH, AND THE LIGHT.') fs.stat(itw, (err, stat) => { assert.ifError(err) assert.ok(stat && stat.isFile(), 'should be file') done() }) }) }) it('should clobber', done => { fse.mkdirp(file, 0o755, err => { assert.ok(err) assert.strictEqual(err.code, 'ENOTDIR') done() }) }) }) ================================================ FILE: lib/mkdirs/__tests__/issue-209.test.js ================================================ 'use strict' const assert = require('assert') const fse = require('../..') /* global describe, it */ describe('mkdirp: issue-209, win32, when bad path, should return a cleaner error', () => { // only seems to be an issue on Windows. if (process.platform !== 'win32') return it('should return a callback', done => { const file = './bad?dir' fse.mkdirp(file, err => { assert(err, 'error is present') assert.strictEqual(err.code, 'EINVAL') const file2 = 'c:\\tmp\foo:moo' fse.mkdirp(file2, err => { assert(err, 'error is present') assert.strictEqual(err.code, 'EINVAL') done() }) }) }) describe('> sync', () => { it('should throw an error', () => { let didErr try { const file = 'c:\\tmp\foo:moo' fse.mkdirpSync(file) } catch { didErr = true } assert(didErr) }) }) }) ================================================ FILE: lib/mkdirs/__tests__/issue-93.test.js ================================================ 'use strict' const os = require('os') const fse = require('../..') const path = require('path') const assert = require('assert') const util = require('util') /* global before, describe, it */ describe('mkdirp: issue-93, win32, when drive does not exist, it should return a cleaner error', () => { let TEST_DIR // only seems to be an issue on Windows. if (process.platform !== 'win32') return before(done => { TEST_DIR = path.join(os.tmpdir(), 'tests', 'fs-extra', 'mkdirp-issue-93') fse.emptyDir(TEST_DIR, err => { assert.ifError(err) done() }) }) it('should return a cleaner error than inifinite loop, stack crash', done => { const file = 'R:\\afasd\\afaff\\fdfd' // hopefully drive 'r' does not exist on appveyor // Different error codes on different Node versions (matches native mkdir behavior) const assertErr = (err) => assert( ['EPERM', 'ENOENT'].includes(err.code), `expected 'EPERM' or 'ENOENT', got ${util.inspect(err.code)}` ) fse.mkdirp(file, err => { assertErr(err) try { fse.mkdirsSync(file) } catch (err) { assertErr(err) } done() }) }) }) ================================================ FILE: lib/mkdirs/__tests__/mkdir.test.js ================================================ 'use strict' const fs = require('fs') const os = require('os') const fse = require('../..') const path = require('path') const assert = require('assert') /* global afterEach, beforeEach, describe, it */ describe('fs-extra', () => { let TEST_DIR beforeEach(done => { TEST_DIR = path.join(os.tmpdir(), 'fs-extra', 'mkdir') fse.emptyDir(TEST_DIR, done) }) afterEach(done => fse.remove(TEST_DIR, done)) describe('+ mkdirs()', () => { it('should make the directory', done => { const dir = path.join(TEST_DIR, 'tmp-' + Date.now() + Math.random()) assert(!fs.existsSync(dir)) fse.mkdirs(dir, err => { assert.ifError(err) assert(fs.existsSync(dir)) done() }) }) it('should make the entire directory path', done => { const dir = path.join(TEST_DIR, 'tmp-' + Date.now() + Math.random()) const newDir = path.join(TEST_DIR, 'dfdf', 'ffff', 'aaa') assert(!fs.existsSync(dir)) fse.mkdirs(newDir, err => { assert.ifError(err) assert(fs.existsSync(newDir)) done() }) }) }) describe('+ mkdirsSync()', () => { it('should make the directory', done => { const dir = path.join(TEST_DIR, 'tmp-' + Date.now() + Math.random()) assert(!fs.existsSync(dir)) fse.mkdirsSync(dir) assert(fs.existsSync(dir)) done() }) it('should make the entire directory path', done => { const dir = path.join(TEST_DIR, 'tmp-' + Date.now() + Math.random()) const newDir = path.join(dir, 'dfdf', 'ffff', 'aaa') assert(!fs.existsSync(newDir)) fse.mkdirsSync(newDir) assert(fs.existsSync(newDir)) done() }) }) }) ================================================ FILE: lib/mkdirs/__tests__/mkdirp.test.js ================================================ 'use strict' const fs = require('fs') const os = require('os') const fse = require('../..') const path = require('path') const assert = require('assert') /* global afterEach, beforeEach, describe, it */ describe('mkdirp / mkdirp', () => { let TEST_DIR beforeEach(done => { TEST_DIR = path.join(os.tmpdir(), 'fs-extra', 'mkdirp') fse.emptyDir(TEST_DIR, done) }) afterEach(done => fse.remove(TEST_DIR, done)) it('should make the dir', done => { const x = Math.floor(Math.random() * Math.pow(16, 4)).toString(16) const y = Math.floor(Math.random() * Math.pow(16, 4)).toString(16) const z = Math.floor(Math.random() * Math.pow(16, 4)).toString(16) const file = path.join(TEST_DIR, x, y, z) fse.mkdirp(file, 0o755, err => { assert.ifError(err) fse.pathExists(file, (err, ex) => { assert.ifError(err) assert.ok(ex, 'file created') fs.stat(file, (err, stat) => { assert.ifError(err) if (os.platform().indexOf('win') === 0) { assert.strictEqual(stat.mode & 0o777, 0o666) } else { assert.strictEqual(stat.mode & 0o777, 0o755) } assert.ok(stat.isDirectory(), 'target not a directory') done() }) }) }) }) }) ================================================ FILE: lib/mkdirs/__tests__/opts-undef.test.js ================================================ 'use strict' const fs = require('fs') const os = require('os') const fse = require('../..') const path = require('path') const assert = require('assert') /* global beforeEach, describe, it */ describe('mkdirs / opts-undef', () => { let TEST_DIR beforeEach(done => { TEST_DIR = path.join(os.tmpdir(), 'fs-extra', 'mkdirs') fse.emptyDir(TEST_DIR, done) }) // https://github.com/substack/node-mkdirp/issues/45 it('should not hang', done => { const newDir = path.join(TEST_DIR, 'doest', 'not', 'exist') assert(!fs.existsSync(newDir)) fse.mkdirs(newDir, undefined, err => { assert.ifError(err) assert(fs.existsSync(newDir)) done() }) }) }) ================================================ FILE: lib/mkdirs/__tests__/perm.test.js ================================================ 'use strict' const fs = require('fs') const os = require('os') const fse = require('../../') const path = require('path') const assert = require('assert') /* global afterEach, beforeEach, describe, it */ describe('mkdirp / perm', () => { let TEST_DIR beforeEach(done => { TEST_DIR = path.join(os.tmpdir(), 'fs-extra', 'mkdirp-perm') fse.emptyDir(TEST_DIR, done) }) afterEach(done => fse.remove(TEST_DIR, done)) it('async perm', done => { const file = path.join(TEST_DIR, (Math.random() * (1 << 30)).toString(16)) fse.mkdirp(file, 0o755, err => { assert.ifError(err) fse.pathExists(file, (err, ex) => { assert.ifError(err) assert.ok(ex, 'file created') fs.stat(file, (err, stat) => { assert.ifError(err) if (os.platform().indexOf('win') === 0) { assert.strictEqual(stat.mode & 0o777, 0o666) } else { assert.strictEqual(stat.mode & 0o777, 0o755) } assert.ok(stat.isDirectory(), 'target not a directory') done() }) }) }) }) it('async root perm', done => { fse.mkdirp(path.join(os.tmpdir(), 'tmp'), 0o755, err => { assert.ifError(err) done() }) }) }) ================================================ FILE: lib/mkdirs/__tests__/perm_sync.test.js ================================================ 'use strict' const fs = require('fs') const os = require('os') const fse = require('../..') const path = require('path') const assert = require('assert') /* global afterEach, beforeEach, describe, it */ describe('mkdirp / perm_sync', () => { let TEST_DIR beforeEach(done => { TEST_DIR = path.join(os.tmpdir(), 'fs-extra', 'mkdirp-perm-sync') fse.emptyDir(TEST_DIR, done) }) afterEach(done => fse.remove(TEST_DIR, done)) it('sync perm', done => { const file = path.join(TEST_DIR, (Math.random() * (1 << 30)).toString(16) + '.json') fse.mkdirpSync(file, 0o755) fse.pathExists(file, (err, ex) => { assert.ifError(err) assert.ok(ex, 'file created') fs.stat(file, (err, stat) => { assert.ifError(err) if (os.platform().indexOf('win') === 0) { assert.strictEqual(stat.mode & 0o777, 0o666) } else { assert.strictEqual(stat.mode & 0o777, 0o755) } assert.ok(stat.isDirectory(), 'target not a directory') done() }) }) }) it('sync root perm', done => { const file = TEST_DIR fse.mkdirpSync(file, 0o755) fse.pathExists(file, (err, ex) => { assert.ifError(err) assert.ok(ex, 'file created') fs.stat(file, (err, stat) => { assert.ifError(err) assert.ok(stat.isDirectory(), 'target not a directory') done() }) }) }) }) ================================================ FILE: lib/mkdirs/__tests__/race.test.js ================================================ 'use strict' const fs = require('fs') const os = require('os') const fse = require('../..') const path = require('path') const assert = require('assert') /* global afterEach, beforeEach, describe, it */ describe('mkdirp / race', () => { let TEST_DIR let file beforeEach(done => { TEST_DIR = path.join(os.tmpdir(), 'fs-extra', 'mkdirp-race') fse.emptyDir(TEST_DIR, err => { assert.ifError(err) const ps = [TEST_DIR] for (let i = 0; i < 15; i++) { const dir = Math.floor(Math.random() * Math.pow(16, 4)).toString(16) ps.push(dir) } file = path.join(...ps) done() }) }) afterEach(done => fse.remove(TEST_DIR, done)) it('race', done => { let res = 2 mk(file, () => --res === 0 ? done() : undefined) mk(file, () => --res === 0 ? done() : undefined) function mk (file, callback) { fse.mkdirp(file, 0o755, err => { assert.ifError(err) fse.pathExists(file, (err, ex) => { assert.ifError(err) assert.ok(ex, 'file created') fs.stat(file, (err, stat) => { assert.ifError(err) if (os.platform().indexOf('win') === 0) { assert.strictEqual(stat.mode & 0o777, 0o666) } else { assert.strictEqual(stat.mode & 0o777, 0o755) } assert.ok(stat.isDirectory(), 'target not a directory') if (callback) callback() }) }) }) } }) }) ================================================ FILE: lib/mkdirs/__tests__/rel.test.js ================================================ 'use strict' const CWD = process.cwd() const fs = require('fs') const os = require('os') const fse = require('../..') const path = require('path') const assert = require('assert') /* global afterEach, beforeEach, describe, it */ describe('mkdirp / relative', () => { let TEST_DIR let file beforeEach(done => { TEST_DIR = path.join(os.tmpdir(), 'fs-extra', 'mkdirp-relative') fse.emptyDir(TEST_DIR, err => { assert.ifError(err) const x = Math.floor(Math.random() * Math.pow(16, 4)).toString(16) const y = Math.floor(Math.random() * Math.pow(16, 4)).toString(16) const z = Math.floor(Math.random() * Math.pow(16, 4)).toString(16) // relative path file = path.join(x, y, z) done() }) }) afterEach(done => fse.remove(TEST_DIR, done)) it('should make the directory with relative path', done => { process.chdir(TEST_DIR) fse.mkdirp(file, 0o755, err => { assert.ifError(err) fse.pathExists(file, (err, ex) => { assert.ifError(err) assert.ok(ex, 'file created') fs.stat(file, (err, stat) => { assert.ifError(err) // restore process.chdir(CWD) if (os.platform().indexOf('win') === 0) { assert.strictEqual(stat.mode & 0o777, 0o666) } else { assert.strictEqual(stat.mode & 0o777, 0o755) } assert.ok(stat.isDirectory(), 'target not a directory') done() }) }) }) }) }) ================================================ FILE: lib/mkdirs/__tests__/root.test.js ================================================ 'use strict' const fs = require('fs') const fse = require('../../') const path = require('path') const assert = require('assert') /* global describe, it */ describe('mkdirp / root', () => { // '/' on unix const dir = path.normalize(path.resolve(path.sep)).toLowerCase() // Windows does not have permission to mkdir on root if (process.platform === 'win32') return it('should', done => { fse.mkdirp(dir, 0o755, err => { if (err) return done(err) fs.stat(dir, (er, stat) => { if (er) return done(er) assert.ok(stat.isDirectory(), 'target is a directory') done() }) }) }) }) ================================================ FILE: lib/mkdirs/__tests__/sync.test.js ================================================ 'use strict' const fs = require('fs') const os = require('os') const fse = require('../..') const path = require('path') const assert = require('assert') /* global afterEach, beforeEach, describe, it */ describe('mkdirp / sync', () => { let TEST_DIR let file beforeEach(done => { TEST_DIR = path.join(os.tmpdir(), 'fs-extra', 'mkdirp-sync') fse.emptyDir(TEST_DIR, err => { assert.ifError(err) const x = Math.floor(Math.random() * Math.pow(16, 4)).toString(16) const y = Math.floor(Math.random() * Math.pow(16, 4)).toString(16) const z = Math.floor(Math.random() * Math.pow(16, 4)).toString(16) file = path.join(TEST_DIR, x, y, z) done() }) }) afterEach(done => fse.remove(TEST_DIR, done)) it('should', done => { try { fse.mkdirpSync(file, 0o755) } catch (err) { assert.fail(err) } fse.pathExists(file, (err, ex) => { assert.ifError(err) assert.ok(ex, 'file created') fs.stat(file, (err, stat) => { assert.ifError(err) // http://stackoverflow.com/questions/592448/c-how-to-set-file-permissions-cross-platform if (os.platform().indexOf('win') === 0) { assert.strictEqual(stat.mode & 0o777, 0o666) } else { assert.strictEqual(stat.mode & 0o777, 0o755) } assert.ok(stat.isDirectory(), 'target not a directory') done() }) }) }) }) ================================================ FILE: lib/mkdirs/index.js ================================================ 'use strict' const u = require('universalify').fromPromise const { makeDir: _makeDir, makeDirSync } = require('./make-dir') const makeDir = u(_makeDir) module.exports = { mkdirs: makeDir, mkdirsSync: makeDirSync, // alias mkdirp: makeDir, mkdirpSync: makeDirSync, ensureDir: makeDir, ensureDirSync: makeDirSync } ================================================ FILE: lib/mkdirs/make-dir.js ================================================ 'use strict' const fs = require('../fs') const { checkPath } = require('./utils') const getMode = options => { const defaults = { mode: 0o777 } if (typeof options === 'number') return options return ({ ...defaults, ...options }).mode } module.exports.makeDir = async (dir, options) => { checkPath(dir) return fs.mkdir(dir, { mode: getMode(options), recursive: true }) } module.exports.makeDirSync = (dir, options) => { checkPath(dir) return fs.mkdirSync(dir, { mode: getMode(options), recursive: true }) } ================================================ FILE: lib/mkdirs/utils.js ================================================ // Adapted from https://github.com/sindresorhus/make-dir // Copyright (c) Sindre Sorhus (sindresorhus.com) // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 'use strict' const path = require('path') // https://github.com/nodejs/node/issues/8987 // https://github.com/libuv/libuv/pull/1088 module.exports.checkPath = function checkPath (pth) { if (process.platform === 'win32') { const pathHasInvalidWinCharacters = /[<>:"|?*]/.test(pth.replace(path.parse(pth).root, '')) if (pathHasInvalidWinCharacters) { const error = new Error(`Path contains invalid characters: ${pth}`) error.code = 'EINVAL' throw error } } } ================================================ FILE: lib/move/__tests__/cross-device-utils.js ================================================ const fs = require('graceful-fs') const path = require('path') const { CROSS_DEVICE_PATH } = process.env let runCrossDeviceTests = !!CROSS_DEVICE_PATH if (runCrossDeviceTests) { // make sure we have permission on device try { fs.writeFileSync(path.join(CROSS_DEVICE_PATH, 'file'), 'hi') } catch { runCrossDeviceTests = false throw new Error(`Can't write to device ${CROSS_DEVICE_PATH}`) } } else console.log('Skipping cross-device move tests') module.exports = { differentDevice: CROSS_DEVICE_PATH, ifCrossDeviceEnabled: (fn) => runCrossDeviceTests ? fn : fn.skip } ================================================ FILE: lib/move/__tests__/move-case-insensitive-paths.test.js ================================================ 'use strict' const assert = require('assert') const os = require('os') const path = require('path') const fs = require('../../') /* global beforeEach, afterEach, describe, it */ describe('+ move() - case insensitive paths', () => { let TEST_DIR = '' let src = '' let dest = '' beforeEach(done => { TEST_DIR = path.join(os.tmpdir(), 'fs-extra', 'move-case-insensitive-paths') fs.emptyDir(TEST_DIR, done) }) afterEach(done => fs.remove(TEST_DIR, done)) describe('> when src is a directory', () => { it('should move successfully', done => { src = path.join(TEST_DIR, 'srcdir') fs.outputFileSync(path.join(src, 'subdir', 'file.txt'), 'some data') dest = path.join(TEST_DIR, 'srcDir') fs.move(src, dest, err => { assert.ifError(err) assert(fs.existsSync(dest)) assert.strictEqual(fs.readFileSync(path.join(dest, 'subdir', 'file.txt'), 'utf8'), 'some data') done() }) }) }) describe('> when src is a file', () => { it('should move successfully', done => { src = path.join(TEST_DIR, 'srcfile') fs.outputFileSync(src, 'some data') dest = path.join(TEST_DIR, 'srcFile') fs.move(src, dest, err => { assert.ifError(err) assert(fs.existsSync(dest)) assert.strictEqual(fs.readFileSync(dest, 'utf8'), 'some data') done() }) }) }) describe('> when src is a symlink', () => { it('should move successfully, symlink dir', done => { src = path.join(TEST_DIR, 'srcdir') fs.outputFileSync(path.join(src, 'subdir', 'file.txt'), 'some data') const srcLink = path.join(TEST_DIR, 'src-symlink') fs.symlinkSync(src, srcLink, 'dir') dest = path.join(TEST_DIR, 'src-Symlink') fs.move(srcLink, dest, err => { assert.ifError(err) assert(fs.existsSync(dest)) assert.strictEqual(fs.readFileSync(path.join(dest, 'subdir', 'file.txt'), 'utf8'), 'some data') const destLink = fs.readlinkSync(dest) assert.strictEqual(destLink, src) done() }) }) it('should move successfully, symlink file', done => { src = path.join(TEST_DIR, 'srcfile') fs.outputFileSync(src, 'some data') const srcLink = path.join(TEST_DIR, 'src-symlink') fs.symlinkSync(src, srcLink, 'file') dest = path.join(TEST_DIR, 'src-Symlink') fs.move(srcLink, dest, err => { assert.ifError(err) assert(fs.existsSync(dest)) assert.strictEqual(fs.readFileSync(dest, 'utf8'), 'some data') const destLink = fs.readlinkSync(dest) assert.strictEqual(destLink, src) done() }) }) }) }) ================================================ FILE: lib/move/__tests__/move-preserve-timestamp.test.js ================================================ 'use strict' const fs = require('../../') const os = require('os') const path = require('path') const utimesSync = require('../../util/utimes').utimesMillisSync const assert = require('assert') const fse = require('../../index') const { differentDevice, ifCrossDeviceEnabled } = require('./cross-device-utils') /* global beforeEach, afterEach, describe, it */ if (process.arch === 'ia32') console.warn('32 bit arch; skipping move timestamp tests') const describeIfPractical = process.arch === 'ia32' ? describe.skip : describe describeIfPractical('move() - across different devices', () => { let TEST_DIR, SRC, DEST, FILES function setupFixture (readonly) { TEST_DIR = path.join(os.tmpdir(), 'fs-extra', 'move-sync-preserve-timestamp') SRC = path.join(differentDevice, 'some/weird/dir-really-weird') DEST = path.join(TEST_DIR, 'dest') FILES = ['a-file', path.join('a-folder', 'another-file'), path.join('a-folder', 'another-folder', 'file3')] const timestamp = Date.now() / 1000 - 5 FILES.forEach(f => { const filePath = path.join(SRC, f) fs.ensureFileSync(filePath) // rewind timestamps to make sure that coarser OS timestamp resolution // does not alter results utimesSync(filePath, timestamp, timestamp) if (readonly) { fs.chmodSync(filePath, 0o444) } }) } afterEach(() => { fse.removeSync(TEST_DIR) fse.removeSync(SRC) }) ifCrossDeviceEnabled(describe)('> default behaviour', () => { ;[ { subcase: 'writable', readonly: false }, { subcase: 'readonly', readonly: true } ].forEach(params => { describe(`>> with ${params.subcase} source files`, () => { beforeEach(() => setupFixture(params.readonly)) it('should have the same timestamps after move', done => { const originalTimestamps = FILES.map(file => { const originalPath = path.join(SRC, file) const originalStat = fs.statSync(originalPath) return { mtime: originalStat.mtime.getTime(), atime: originalStat.atime.getTime() } }) fse.move(SRC, DEST, {}, (err) => { if (err) return done(err) FILES.forEach(testFile({}, originalTimestamps)) done() }) }) }) }) }) function testFile (options, originalTimestamps) { return function (file, idx) { const originalTimestamp = originalTimestamps[idx] const currentPath = path.join(DEST, file) const currentStats = fs.statSync(currentPath) assert.strictEqual(currentStats.mtime.getTime(), originalTimestamp.mtime, 'different mtime values') assert.strictEqual(currentStats.atime.getTime(), originalTimestamp.atime, 'different atime values') } } }) ================================================ FILE: lib/move/__tests__/move-prevent-moving-identical.test.js ================================================ 'use strict' const assert = require('assert') const os = require('os') const path = require('path') const fs = require('../../') const klawSync = require('klaw-sync') /* global beforeEach, afterEach, describe, it */ describe('+ move() - prevent moving identical files and dirs', () => { let TEST_DIR = '' let src = '' let dest = '' beforeEach(done => { TEST_DIR = path.join(os.tmpdir(), 'fs-extra', 'move-prevent-moving-identical') fs.emptyDir(TEST_DIR, done) }) afterEach(done => fs.remove(TEST_DIR, done)) it('should return an error if src and dest are the same', done => { const fileSrc = path.join(TEST_DIR, 'TEST_fs-extra_move') const fileDest = path.join(TEST_DIR, 'TEST_fs-extra_move') fs.ensureFileSync(fileSrc) fs.move(fileSrc, fileDest, err => { assert.strictEqual(err.message, 'Source and destination must not be the same.') done() }) }) describe('dest with parent symlink', () => { describe('first parent is symlink', () => { it('should error when src is file', done => { const src = path.join(TEST_DIR, 'a', 'file.txt') const dest = path.join(TEST_DIR, 'b', 'file.txt') const srcParent = path.join(TEST_DIR, 'a') const destParent = path.join(TEST_DIR, 'b') fs.ensureFileSync(src) fs.ensureSymlinkSync(srcParent, destParent, 'dir') fs.move(src, dest, err => { assert.strictEqual(err.message, 'Source and destination must not be the same.') assert(fs.existsSync(src)) done() }) }) it('should error when src is directory', done => { const src = path.join(TEST_DIR, 'a', 'foo') const dest = path.join(TEST_DIR, 'b', 'foo') const srcParent = path.join(TEST_DIR, 'a') const destParent = path.join(TEST_DIR, 'b') fs.ensureDirSync(src) fs.ensureSymlinkSync(srcParent, destParent, 'dir') fs.move(src, dest, err => { assert.strictEqual(err.message, 'Source and destination must not be the same.') assert(fs.existsSync(src)) done() }) }) }) describe('nested dest', () => { it('should error when src is file', done => { const src = path.join(TEST_DIR, 'a', 'dir', 'file.txt') const dest = path.join(TEST_DIR, 'b', 'dir', 'file.txt') const srcParent = path.join(TEST_DIR, 'a') const destParent = path.join(TEST_DIR, 'b') fs.ensureFileSync(src) fs.ensureSymlinkSync(srcParent, destParent, 'dir') fs.move(src, dest, err => { assert.strictEqual(err.message, 'Source and destination must not be the same.') assert(fs.existsSync(src)) done() }) }) it('should error when src is directory', done => { const src = path.join(TEST_DIR, 'a', 'dir', 'foo') const dest = path.join(TEST_DIR, 'b', 'dir', 'foo') const srcParent = path.join(TEST_DIR, 'a') const destParent = path.join(TEST_DIR, 'b') fs.ensureDirSync(src) fs.ensureSymlinkSync(srcParent, destParent, 'dir') fs.move(src, dest, err => { assert.strictEqual(err.message, 'Source and destination must not be the same.') assert(fs.existsSync(src)) done() }) }) }) }) // src is directory: // src is regular, dest is symlink // src is symlink, dest is regular // src is symlink, dest is symlink describe('> when src is a directory', () => { describe('>> when src is regular and dest is a symlink that points to src', () => { it('should error if dereference is true', done => { src = path.join(TEST_DIR, 'src') fs.mkdirsSync(src) const subdir = path.join(TEST_DIR, 'src', 'subdir') fs.mkdirsSync(subdir) fs.writeFileSync(path.join(subdir, 'file.txt'), 'some data') const destLink = path.join(TEST_DIR, 'dest-symlink') fs.symlinkSync(src, destLink, 'dir') const oldlen = klawSync(src).length fs.move(src, destLink, { dereference: true }, err => { assert.strictEqual(err.message, 'Source and destination must not be the same.') const newlen = klawSync(src).length assert.strictEqual(newlen, oldlen) const link = fs.readlinkSync(destLink) assert.strictEqual(link, src) done() }) }) }) describe('>> when src is a symlink that points to a regular dest', () => { it('should throw error', done => { dest = path.join(TEST_DIR, 'dest') fs.mkdirsSync(dest) const subdir = path.join(TEST_DIR, 'dest', 'subdir') fs.mkdirsSync(subdir) fs.writeFileSync(path.join(subdir, 'file.txt'), 'some data') const srcLink = path.join(TEST_DIR, 'src-symlink') fs.symlinkSync(dest, srcLink, 'dir') const oldlen = klawSync(dest).length fs.move(srcLink, dest, err => { assert.ok(err) // assert nothing copied const newlen = klawSync(dest).length assert.strictEqual(newlen, oldlen) const link = fs.readlinkSync(srcLink) assert.strictEqual(link, dest) done() }) }) }) describe('>> when src and dest are symlinks that point to the exact same path', () => { it('should error src and dest are the same and dereference is true', done => { src = path.join(TEST_DIR, 'src') fs.mkdirsSync(src) const srcLink = path.join(TEST_DIR, 'src_symlink') fs.symlinkSync(src, srcLink, 'dir') const destLink = path.join(TEST_DIR, 'dest_symlink') fs.symlinkSync(src, destLink, 'dir') const srclenBefore = klawSync(srcLink).length const destlenBefore = klawSync(destLink).length fs.move(srcLink, destLink, { dereference: true }, err => { assert.strictEqual(err.message, 'Source and destination must not be the same.') const srclenAfter = klawSync(srcLink).length assert.strictEqual(srclenAfter, srclenBefore, 'src length should not change') const destlenAfter = klawSync(destLink).length assert.strictEqual(destlenAfter, destlenBefore, 'dest length should not change') const srcln = fs.readlinkSync(srcLink) assert.strictEqual(srcln, src) const destln = fs.readlinkSync(destLink) assert.strictEqual(destln, src) done() }) }) }) }) // src is file: // src is regular, dest is symlink // src is symlink, dest is regular // src is symlink, dest is symlink describe('> when src is a file', () => { describe('>> when src is regular and dest is a symlink that points to src', () => { it('should error if dereference is true', done => { src = path.join(TEST_DIR, 'src.txt') fs.outputFileSync(src, 'some data') const destLink = path.join(TEST_DIR, 'dest-symlink') fs.symlinkSync(src, destLink, 'file') fs.move(src, destLink, { dereference: true }, err => { assert.strictEqual(err.message, 'Source and destination must not be the same.') done() }) }) }) describe('>> when src is a symlink that points to a regular dest', () => { it('should throw error if dereferene is true', done => { dest = path.join(TEST_DIR, 'dest', 'somefile.txt') fs.outputFileSync(dest, 'some data') const srcLink = path.join(TEST_DIR, 'src-symlink') fs.symlinkSync(dest, srcLink, 'file') fs.move(srcLink, dest, { dereference: true }, err => { assert.strictEqual(err.message, 'Source and destination must not be the same.') const link = fs.readlinkSync(srcLink) assert.strictEqual(link, dest) assert(fs.readFileSync(link, 'utf8'), 'some data') done() }) }) }) describe('>> when src and dest are symlinks that point to the exact same path', () => { it('should error src and dest are the same and dereferene is true', done => { src = path.join(TEST_DIR, 'src', 'srcfile.txt') fs.outputFileSync(src, 'src data') const srcLink = path.join(TEST_DIR, 'src_symlink') fs.symlinkSync(src, srcLink, 'file') const destLink = path.join(TEST_DIR, 'dest_symlink') fs.symlinkSync(src, destLink, 'file') fs.move(srcLink, destLink, { dereference: true }, err => { assert.strictEqual(err.message, 'Source and destination must not be the same.') const srcln = fs.readlinkSync(srcLink) assert.strictEqual(srcln, src) const destln = fs.readlinkSync(destLink) assert.strictEqual(destln, src) assert(fs.readFileSync(srcln, 'utf8'), 'src data') assert(fs.readFileSync(destln, 'utf8'), 'src data') done() }) }) }) }) }) ================================================ FILE: lib/move/__tests__/move-prevent-moving-into-itself.test.js ================================================ 'use strict' const assert = require('assert') const os = require('os') const path = require('path') const fs = require('../../') const klawSync = require('klaw-sync') /* global beforeEach, afterEach, describe, it */ // these files are used for all tests const FILES = [ 'file0.txt', path.join('dir1', 'file1.txt'), path.join('dir1', 'dir2', 'file2.txt'), path.join('dir1', 'dir2', 'dir3', 'file3.txt') ] const dat0 = 'file0' const dat1 = 'file1' const dat2 = 'file2' const dat3 = 'file3' describe('+ move() - prevent moving into itself', () => { let TEST_DIR, src beforeEach(() => { TEST_DIR = path.join(os.tmpdir(), 'fs-extra', 'move-prevent-moving-into-itself') src = path.join(TEST_DIR, 'src') fs.mkdirpSync(src) fs.outputFileSync(path.join(src, FILES[0]), dat0) fs.outputFileSync(path.join(src, FILES[1]), dat1) fs.outputFileSync(path.join(src, FILES[2]), dat2) fs.outputFileSync(path.join(src, FILES[3]), dat3) }) afterEach(() => fs.removeSync(TEST_DIR)) describe('> when source is a file', () => { it('should move the file successfully even if dest parent is a subdir of src', done => { const srcFile = path.join(TEST_DIR, 'src', 'srcfile.txt') const destFile = path.join(TEST_DIR, 'src', 'dest', 'destfile.txt') fs.writeFileSync(srcFile, dat0) fs.move(srcFile, destFile, err => { assert.ifError(err) assert(fs.existsSync(destFile)) const out = fs.readFileSync(destFile, 'utf8') assert.strictEqual(out, dat0, 'file contents matched') done() }) }) it("should move the file successfully even when dest parent is 'src/dest'", done => { const destFile = path.join(TEST_DIR, 'src', 'dest', 'destfile.txt') return testSuccessFile(src, destFile, done) }) it("should move the file successfully when dest parent is 'src/src_dest'", done => { const destFile = path.join(TEST_DIR, 'src', 'src_dest', 'destfile.txt') return testSuccessFile(src, destFile, done) }) it("should move the file successfully when dest parent is 'src/dest_src'", done => { const destFile = path.join(TEST_DIR, 'src', 'dest_src', 'destfile.txt') return testSuccessFile(src, destFile, done) }) it("should move the file successfully when dest parent is 'src/dest/src'", done => { const destFile = path.join(TEST_DIR, 'src', 'dest', 'src', 'destfile.txt') return testSuccessFile(src, destFile, done) }) it("should move the file successfully when dest parent is 'srcsrc/dest'", done => { const destFile = path.join(TEST_DIR, 'srcsrc', 'dest', 'destfile.txt') return testSuccessFile(src, destFile, done) }) }) describe('> when source is a directory', () => { describe('>> when dest is a directory', () => { it('of not itself', done => { const dest = path.join(TEST_DIR, src.replace(/^\w:/, '')) return testSuccessDir(src, dest, done) }) it('of itself', done => { const dest = path.join(src, 'dest') return testError(src, dest, done) }) it("should move the directory successfully when dest is 'src_dest'", done => { const dest = path.join(TEST_DIR, 'src_dest') return testSuccessDir(src, dest, done) }) it("should move the directory successfully when dest is 'src-dest'", done => { const dest = path.join(TEST_DIR, 'src-dest') return testSuccessDir(src, dest, done) }) it("should move the directory successfully when dest is 'dest_src'", done => { const dest = path.join(TEST_DIR, 'dest_src') return testSuccessDir(src, dest, done) }) it("should move the directory successfully when dest is 'src_dest/src'", done => { const dest = path.join(TEST_DIR, 'src_dest', 'src') return testSuccessDir(src, dest, done) }) it("should move the directory successfully when dest is 'src-dest/src'", done => { const dest = path.join(TEST_DIR, 'src-dest', 'src') return testSuccessDir(src, dest, done) }) it("should move the directory successfully when dest is 'dest_src/src'", done => { const dest = path.join(TEST_DIR, 'dest_src', 'src') return testSuccessDir(src, dest, done) }) it("should move the directory successfully when dest is 'src_src/dest'", done => { const dest = path.join(TEST_DIR, 'src_src', 'dest') return testSuccessDir(src, dest, done) }) it("should move the directory successfully when dest is 'src-src/dest'", done => { const dest = path.join(TEST_DIR, 'src-src', 'dest') return testSuccessDir(src, dest, done) }) it("should move the directory successfully when dest is 'srcsrc/dest'", done => { const dest = path.join(TEST_DIR, 'srcsrc', 'dest') return testSuccessDir(src, dest, done) }) it("should move the directory successfully when dest is 'dest/src'", done => { const dest = path.join(TEST_DIR, 'dest', 'src') return testSuccessDir(src, dest, done) }) it('should move the directory successfully when dest is very nested that all its parents need to be created', done => { const dest = path.join(TEST_DIR, 'dest', 'src', 'foo', 'bar', 'baz', 'qux', 'quux', 'waldo', 'grault', 'garply', 'fred', 'plugh', 'thud', 'some', 'highly', 'deeply', 'badly', 'nasty', 'crazy', 'mad', 'nested', 'dest') return testSuccessDir(src, dest, done) }) it("should error when dest is 'src/dest'", done => { const dest = path.join(TEST_DIR, 'src', 'dest') return testError(src, dest, done) }) it("should error when dest is 'src/src_dest'", done => { const dest = path.join(TEST_DIR, 'src', 'src_dest') return testError(src, dest, done) }) it("should error when dest is 'src/dest_src'", done => { const dest = path.join(TEST_DIR, 'src', 'dest_src') return testError(src, dest, done) }) it("should error when dest is 'src/dest/src'", done => { const dest = path.join(TEST_DIR, 'src', 'dest', 'src') return testError(src, dest, done) }) }) describe('>> when dest is a symlink', () => { it('should error when dest is a subdirectory of src (bind-mounted directory with subdirectory)', done => { const destLink = path.join(TEST_DIR, 'dest-symlink') fs.symlinkSync(src, destLink, 'dir') const srclenBefore = klawSync(src).length assert(srclenBefore > 2) const dest = path.join(destLink, 'dir1') assert(fs.existsSync(dest)) fs.move(src, dest, err => { assert.strictEqual(err.message, `Cannot move '${src}' to a subdirectory of itself, '${dest}'.`) const srclenAfter = klawSync(src).length assert.strictEqual(srclenAfter, srclenBefore, 'src length should not change') const link = fs.readlinkSync(destLink) assert.strictEqual(link, src) done() }) }) it('should error when dest is a subdirectory of src (more than one level depth)', done => { const destLink = path.join(TEST_DIR, 'dest-symlink') fs.symlinkSync(src, destLink, 'dir') const srclenBefore = klawSync(src).length assert(srclenBefore > 2) const dest = path.join(destLink, 'dir1', 'dir2') assert(fs.existsSync(dest)) fs.move(src, dest, err => { assert.strictEqual(err.message, `Cannot move '${src}' to a subdirectory of itself, '${path.join(destLink, 'dir1')}'.`) const srclenAfter = klawSync(src).length assert.strictEqual(srclenAfter, srclenBefore, 'src length should not change') const link = fs.readlinkSync(destLink) assert.strictEqual(link, src) done() }) }) }) }) describe('> when source is a symlink', () => { describe('>> when dest is a directory', () => { it('should error when resolved src path points to dest', done => { const srcLink = path.join(TEST_DIR, 'src-symlink') fs.symlinkSync(src, srcLink, 'dir') const dest = path.join(TEST_DIR, 'src') fs.move(srcLink, dest, err => { assert(err) // assert source not affected const link = fs.readlinkSync(srcLink) assert.strictEqual(link, src) done() }) }) it('should error when dest is a subdir of resolved src path', done => { const srcLink = path.join(TEST_DIR, 'src-symlink') fs.symlinkSync(src, srcLink, 'dir') const dest = path.join(TEST_DIR, 'src', 'some', 'nested', 'dest') fs.mkdirsSync(dest) fs.move(srcLink, dest, err => { assert(err) const link = fs.readlinkSync(srcLink) assert.strictEqual(link, src) done() }) }) it('should error when resolved src path is a subdir of dest', done => { const dest = path.join(TEST_DIR, 'dest') const resolvedSrcPath = path.join(dest, 'contains', 'src') const srcLink = path.join(TEST_DIR, 'src-symlink') fs.copySync(src, resolvedSrcPath) // make symlink that points to a subdir in dest fs.symlinkSync(resolvedSrcPath, srcLink, 'dir') fs.move(srcLink, dest, err => { assert(err) done() }) }) it("should move the directory successfully when dest is 'src_src/dest'", done => { const srcLink = path.join(TEST_DIR, 'src-symlink') fs.symlinkSync(src, srcLink, 'dir') const dest = path.join(TEST_DIR, 'src_src', 'dest') testSuccessDir(srcLink, dest, () => { const link = fs.readlinkSync(dest) assert.strictEqual(link, src) done() }) }) it("should move the directory successfully when dest is 'srcsrc/dest'", done => { const srcLink = path.join(TEST_DIR, 'src-symlink') fs.symlinkSync(src, srcLink, 'dir') const dest = path.join(TEST_DIR, 'srcsrc', 'dest') testSuccessDir(srcLink, dest, () => { const link = fs.readlinkSync(dest) assert.strictEqual(link, src) done() }) }) }) describe('>> when dest is a symlink', () => { it('should error when resolved dest path is exactly the same as resolved src path and dereferene is true', done => { const srcLink = path.join(TEST_DIR, 'src-symlink') fs.symlinkSync(src, srcLink, 'dir') const destLink = path.join(TEST_DIR, 'dest-symlink') fs.symlinkSync(src, destLink, 'dir') const srclenBefore = klawSync(srcLink).length const destlenBefore = klawSync(destLink).length assert(srclenBefore > 2) assert(destlenBefore > 2) fs.move(srcLink, destLink, { dereference: true }, err => { assert.strictEqual(err.message, 'Source and destination must not be the same.') const srclenAfter = klawSync(srcLink).length assert.strictEqual(srclenAfter, srclenBefore, 'src length should not change') const destlenAfter = klawSync(destLink).length assert.strictEqual(destlenAfter, destlenBefore, 'dest length should not change') const srcln = fs.readlinkSync(srcLink) assert.strictEqual(srcln, src) const destln = fs.readlinkSync(destLink) assert.strictEqual(destln, src) done() }) }) }) }) }) function testSuccessFile (src, destFile, done) { const srcFile = path.join(src, FILES[0]) fs.move(srcFile, destFile, err => { assert.ifError(err) const f0 = fs.readFileSync(destFile, 'utf8') assert.strictEqual(f0, dat0, 'file contents matched') assert(!fs.existsSync(srcFile)) return done() }) } function testSuccessDir (src, dest, done) { const srclen = klawSync(src).length assert(srclen > 2) // assert src has contents fs.move(src, dest, err => { assert.ifError(err) const destlen = klawSync(dest).length assert.strictEqual(destlen, srclen, 'src and dest length should be equal') const f0 = fs.readFileSync(path.join(dest, FILES[0]), 'utf8') const f1 = fs.readFileSync(path.join(dest, FILES[1]), 'utf8') const f2 = fs.readFileSync(path.join(dest, FILES[2]), 'utf8') const f3 = fs.readFileSync(path.join(dest, FILES[3]), 'utf8') assert.strictEqual(f0, dat0, 'file contents matched') assert.strictEqual(f1, dat1, 'file contents matched') assert.strictEqual(f2, dat2, 'file contents matched') assert.strictEqual(f3, dat3, 'file contents matched') assert(!fs.existsSync(src)) return done() }) } function testError (src, dest, done) { fs.move(src, dest, err => { assert(err) assert.strictEqual(err.message, `Cannot move '${src}' to a subdirectory of itself, '${dest}'.`) assert(fs.existsSync(src)) assert(!fs.existsSync(dest)) return done() }) } ================================================ FILE: lib/move/__tests__/move-sync-case-insensitive-paths.test.js ================================================ 'use strict' const assert = require('assert') const os = require('os') const path = require('path') const fs = require('../../') /* global beforeEach, afterEach, describe, it */ describe('+ moveSync() - case insensitive paths', () => { let TEST_DIR = '' let src = '' let dest = '' beforeEach(done => { TEST_DIR = path.join(os.tmpdir(), 'fs-extra', 'move-sync-case-insensitive-paths') fs.emptyDir(TEST_DIR, done) }) afterEach(() => fs.removeSync(TEST_DIR)) describe('> when src is a directory', () => { it('should move successfully', () => { src = path.join(TEST_DIR, 'srcdir') fs.outputFileSync(path.join(src, 'subdir', 'file.txt'), 'some data') dest = path.join(TEST_DIR, 'srcDir') fs.moveSync(src, dest) assert(fs.existsSync(dest)) assert.strictEqual(fs.readFileSync(path.join(dest, 'subdir', 'file.txt'), 'utf8'), 'some data') }) }) describe('> when src is a file', () => { it('should move successfully', () => { src = path.join(TEST_DIR, 'srcfile') fs.outputFileSync(src, 'some data') dest = path.join(TEST_DIR, 'srcFile') fs.moveSync(src, dest) assert(fs.existsSync(dest)) assert.strictEqual(fs.readFileSync(dest, 'utf8'), 'some data') }) }) describe('> when src is a symlink', () => { it('should move successfully, symlink dir', () => { src = path.join(TEST_DIR, 'srcdir') fs.outputFileSync(path.join(src, 'subdir', 'file.txt'), 'some data') const srcLink = path.join(TEST_DIR, 'src-symlink') fs.symlinkSync(src, srcLink, 'dir') dest = path.join(TEST_DIR, 'src-Symlink') fs.moveSync(srcLink, dest) assert(fs.existsSync(dest)) assert.strictEqual(fs.readFileSync(path.join(dest, 'subdir', 'file.txt'), 'utf8'), 'some data') const destLink = fs.readlinkSync(dest) assert.strictEqual(destLink, src) }) it('should move successfully, symlink file', () => { src = path.join(TEST_DIR, 'srcfile') fs.outputFileSync(src, 'some data') const srcLink = path.join(TEST_DIR, 'src-symlink') fs.symlinkSync(src, srcLink, 'file') dest = path.join(TEST_DIR, 'src-Symlink') fs.moveSync(srcLink, dest) assert(fs.existsSync(dest)) assert.strictEqual(fs.readFileSync(dest, 'utf8'), 'some data') const destLink = fs.readlinkSync(dest) assert.strictEqual(destLink, src) }) }) }) ================================================ FILE: lib/move/__tests__/move-sync-preserve-timestamp.test.js ================================================ 'use strict' const fs = require('../../') const os = require('os') const path = require('path') const utimesSync = require('../../util/utimes').utimesMillisSync const assert = require('assert') const fse = require('../../index') const { differentDevice, ifCrossDeviceEnabled } = require('./cross-device-utils') /* global beforeEach, afterEach, describe, it */ if (process.arch === 'ia32') console.warn('32 bit arch; skipping move timestamp tests') const describeIfPractical = process.arch === 'ia32' ? describe.skip : describe describeIfPractical('moveSync() - across different devices', () => { let TEST_DIR, SRC, DEST, FILES function setupFixture (readonly) { TEST_DIR = path.join(os.tmpdir(), 'fs-extra', 'move-sync-preserve-timestamp') SRC = path.join(differentDevice, 'some/weird/dir-really-weird') DEST = path.join(TEST_DIR, 'dest') FILES = ['a-file', path.join('a-folder', 'another-file'), path.join('a-folder', 'another-folder', 'file3')] const timestamp = Date.now() / 1000 - 5 FILES.forEach(f => { const filePath = path.join(SRC, f) fs.ensureFileSync(filePath) // rewind timestamps to make sure that coarser OS timestamp resolution // does not alter results utimesSync(filePath, timestamp, timestamp) if (readonly) { fs.chmodSync(filePath, 0o444) } }) } afterEach(() => { fse.removeSync(TEST_DIR) fse.removeSync(SRC) }) ifCrossDeviceEnabled(describe)('> default behaviour', () => { ;[ { subcase: 'writable', readonly: false }, { subcase: 'readonly', readonly: true } ].forEach(params => { describe(`>> with ${params.subcase} source files`, () => { beforeEach(() => setupFixture(params.readonly)) it('should have the same timestamps after move', () => { const originalTimestamps = FILES.map(file => { const originalPath = path.join(SRC, file) const originalStat = fs.statSync(originalPath) return { mtime: originalStat.mtime.getTime(), atime: originalStat.atime.getTime() } }) fse.moveSync(SRC, DEST, {}) FILES.forEach(testFile({}, originalTimestamps)) }) }) }) }) function testFile (options, originalTimestamps) { return function (file, idx) { const originalTimestamp = originalTimestamps[idx] const currentPath = path.join(DEST, file) const currentStats = fs.statSync(currentPath) // Windows sub-second precision fixed: https://github.com/nodejs/io.js/issues/2069 assert.strictEqual(currentStats.mtime.getTime(), originalTimestamp.mtime, 'different mtime values') assert.strictEqual(currentStats.atime.getTime(), originalTimestamp.atime, 'different atime values') } } }) ================================================ FILE: lib/move/__tests__/move-sync-prevent-moving-identical.test.js ================================================ 'use strict' const assert = require('assert') const os = require('os') const path = require('path') const fs = require('../../') const klawSync = require('klaw-sync') /* global beforeEach, afterEach, describe, it */ describe('+ moveSync() - prevent moving identical files and dirs', () => { let TEST_DIR = '' let src = '' let dest = '' beforeEach(done => { TEST_DIR = path.join(os.tmpdir(), 'fs-extra', 'move-sync-prevent-moving-identical') fs.emptyDir(TEST_DIR, done) }) afterEach(done => fs.remove(TEST_DIR, done)) it('should return an error if src and dest are the same', () => { const fileSrc = path.join(TEST_DIR, 'TEST_fs-extra_move_sync') const fileDest = path.join(TEST_DIR, 'TEST_fs-extra_move_sync') fs.ensureFileSync(fileSrc) try { fs.moveSync(fileSrc, fileDest) } catch (err) { assert.strictEqual(err.message, 'Source and destination must not be the same.') } }) describe('dest with parent symlink', () => { describe('first parent is symlink', () => { it('should error when src is file', () => { const src = path.join(TEST_DIR, 'a', 'file.txt') const dest = path.join(TEST_DIR, 'b', 'file.txt') const srcParent = path.join(TEST_DIR, 'a') const destParent = path.join(TEST_DIR, 'b') fs.ensureFileSync(src) fs.ensureSymlinkSync(srcParent, destParent, 'dir') try { fs.moveSync(src, dest) } catch (err) { assert.strictEqual(err.message, 'Source and destination must not be the same.') } finally { assert(fs.existsSync(src)) } }) it('should error when src is directory', () => { const src = path.join(TEST_DIR, 'a', 'foo') const dest = path.join(TEST_DIR, 'b', 'foo') const srcParent = path.join(TEST_DIR, 'a') const destParent = path.join(TEST_DIR, 'b') fs.ensureDirSync(src) fs.ensureSymlinkSync(srcParent, destParent, 'dir') try { fs.moveSync(src, dest) } catch (err) { assert.strictEqual(err.message, 'Source and destination must not be the same.') } finally { assert(fs.existsSync(src)) } }) }) describe('nested dest', () => { it('should error when src is file', () => { const src = path.join(TEST_DIR, 'a', 'dir', 'file.txt') const dest = path.join(TEST_DIR, 'b', 'dir', 'file.txt') const srcParent = path.join(TEST_DIR, 'a') const destParent = path.join(TEST_DIR, 'b') fs.ensureFileSync(src) fs.ensureSymlinkSync(srcParent, destParent, 'dir') try { fs.moveSync(src, dest) } catch (err) { assert.strictEqual(err.message, 'Source and destination must not be the same.') } finally { assert(fs.existsSync(src)) } }) it('should error when src is directory', () => { const src = path.join(TEST_DIR, 'a', 'dir', 'foo') const dest = path.join(TEST_DIR, 'b', 'dir', 'foo') const srcParent = path.join(TEST_DIR, 'a') const destParent = path.join(TEST_DIR, 'b') fs.ensureDirSync(src) fs.ensureSymlinkSync(srcParent, destParent, 'dir') try { fs.moveSync(src, dest) } catch (err) { assert.strictEqual(err.message, 'Source and destination must not be the same.') } finally { assert(fs.existsSync(src)) } }) }) }) // src is directory: // src is regular, dest is symlink // src is symlink, dest is regular // src is symlink, dest is symlink describe('> when src is a directory', () => { describe('>> when src is regular and dest is a symlink that points to src', () => { it('should error if dereferene is true', () => { src = path.join(TEST_DIR, 'src') fs.mkdirsSync(src) const subdir = path.join(TEST_DIR, 'src', 'subdir') fs.mkdirsSync(subdir) fs.writeFileSync(path.join(subdir, 'file.txt'), 'some data') const destLink = path.join(TEST_DIR, 'dest-symlink') fs.symlinkSync(src, destLink, 'dir') const oldlen = klawSync(src).length try { fs.moveSync(src, destLink, { dereference: true }) } catch (err) { assert.strictEqual(err.message, 'Source and destination must not be the same.') } const newlen = klawSync(src).length assert.strictEqual(newlen, oldlen) const link = fs.readlinkSync(destLink) assert.strictEqual(link, src) }) }) describe('>> when src is a symlink that points to a regular dest', () => { it('should throw error', () => { dest = path.join(TEST_DIR, 'dest') fs.mkdirsSync(dest) const subdir = path.join(TEST_DIR, 'dest', 'subdir') fs.mkdirsSync(subdir) fs.writeFileSync(path.join(subdir, 'file.txt'), 'some data') const srcLink = path.join(TEST_DIR, 'src-symlink') fs.symlinkSync(dest, srcLink, 'dir') const oldlen = klawSync(dest).length try { fs.moveSync(srcLink, dest) } catch (err) { assert(err) } // assert nothing copied const newlen = klawSync(dest).length assert.strictEqual(newlen, oldlen) const link = fs.readlinkSync(srcLink) assert.strictEqual(link, dest) }) }) describe('>> when src and dest are symlinks that point to the exact same path', () => { it('should error if src and dest are the same and dereference is true', () => { src = path.join(TEST_DIR, 'src') fs.mkdirsSync(src) const srcLink = path.join(TEST_DIR, 'src_symlink') fs.symlinkSync(src, srcLink, 'dir') const destLink = path.join(TEST_DIR, 'dest_symlink') fs.symlinkSync(src, destLink, 'dir') const srclenBefore = klawSync(srcLink).length const destlenBefore = klawSync(destLink).length try { fs.moveSync(srcLink, destLink, { dereference: true }) } catch (err) { assert.strictEqual(err.message, 'Source and destination must not be the same.') } const srclenAfter = klawSync(srcLink).length assert.strictEqual(srclenAfter, srclenBefore, 'src length should not change') const destlenAfter = klawSync(destLink).length assert.strictEqual(destlenAfter, destlenBefore, 'dest length should not change') const srcln = fs.readlinkSync(srcLink) assert.strictEqual(srcln, src) const destln = fs.readlinkSync(destLink) assert.strictEqual(destln, src) }) }) }) // src is file: // src is regular, dest is symlink // src is symlink, dest is regular // src is symlink, dest is symlink describe('> when src is a file', () => { describe('>> when src is regular and dest is a symlink that points to src', () => { it('should error if dereference is true', () => { src = path.join(TEST_DIR, 'src', 'somefile.txt') fs.ensureFileSync(src) fs.writeFileSync(src, 'some data') const destLink = path.join(TEST_DIR, 'dest-symlink') fs.symlinkSync(src, destLink, 'file') try { fs.moveSync(src, destLink, { dereference: true }) } catch (err) { assert.strictEqual(err.message, 'Source and destination must not be the same.') } const link = fs.readlinkSync(destLink) assert.strictEqual(link, src) assert(fs.readFileSync(link, 'utf8'), 'some data') }) }) describe('>> when src is a symlink that points to a regular dest', () => { it('should throw error', () => { dest = path.join(TEST_DIR, 'dest', 'somefile.txt') fs.outputFileSync(dest, 'some data') const srcLink = path.join(TEST_DIR, 'src-symlink') fs.symlinkSync(dest, srcLink, 'file') try { fs.moveSync(srcLink, dest) } catch (err) { assert.ok(err) } const link = fs.readlinkSync(srcLink) assert.strictEqual(link, dest) assert(fs.readFileSync(link, 'utf8'), 'some data') }) }) describe('>> when src and dest are symlinks that point to the exact same path', () => { it('should error if src and dest are the same and dereference is true', () => { src = path.join(TEST_DIR, 'src', 'srcfile.txt') fs.outputFileSync(src, 'src data') const srcLink = path.join(TEST_DIR, 'src_symlink') fs.symlinkSync(src, srcLink, 'file') const destLink = path.join(TEST_DIR, 'dest_symlink') fs.symlinkSync(src, destLink, 'file') try { fs.moveSync(srcLink, destLink, { dereference: true }) } catch (err) { assert.strictEqual(err.message, 'Source and destination must not be the same.') } const srcln = fs.readlinkSync(srcLink) assert.strictEqual(srcln, src) const destln = fs.readlinkSync(destLink) assert.strictEqual(destln, src) assert(fs.readFileSync(srcln, 'utf8'), 'src data') assert(fs.readFileSync(destln, 'utf8'), 'src data') }) }) }) }) ================================================ FILE: lib/move/__tests__/move-sync-prevent-moving-into-itself.test.js ================================================ 'use strict' const assert = require('assert') const os = require('os') const path = require('path') const fs = require('../../') const klawSync = require('klaw-sync') /* global beforeEach, afterEach, describe, it */ // these files are used for all tests const FILES = [ 'file0.txt', path.join('dir1', 'file1.txt'), path.join('dir1', 'dir2', 'file2.txt'), path.join('dir1', 'dir2', 'dir3', 'file3.txt') ] const dat0 = 'file0' const dat1 = 'file1' const dat2 = 'file2' const dat3 = 'file3' describe('+ moveSync() - prevent moving into itself', () => { let TEST_DIR, src beforeEach(done => { TEST_DIR = path.join(os.tmpdir(), 'fs-extra', 'move-sync-prevent-moving-into-itself') src = path.join(TEST_DIR, 'src') fs.mkdirpSync(src) fs.outputFileSync(path.join(src, FILES[0]), dat0) fs.outputFileSync(path.join(src, FILES[1]), dat1) fs.outputFileSync(path.join(src, FILES[2]), dat2) fs.outputFileSync(path.join(src, FILES[3]), dat3) done() }) afterEach(done => fs.remove(TEST_DIR, done)) describe('> when source is a file', () => { it('should move the file successfully even if dest parent is a subdir of src', () => { const srcFile = path.join(TEST_DIR, 'src', 'srcfile.txt') const destFile = path.join(TEST_DIR, 'src', 'dest', 'destfile.txt') fs.writeFileSync(srcFile, dat0) fs.moveSync(srcFile, destFile) assert(fs.existsSync(destFile)) const out = fs.readFileSync(destFile, 'utf8') assert.strictEqual(out, dat0, 'file contents matched') }) }) describe('> when source is a file', () => { it("should move the file successfully even when dest parent is 'src/dest'", () => { const destFile = path.join(TEST_DIR, 'src', 'dest', 'destfile.txt') return testSuccessFile(src, destFile) }) it("should move the file successfully when dest parent is 'src/src_dest'", () => { const destFile = path.join(TEST_DIR, 'src', 'src_dest', 'destfile.txt') return testSuccessFile(src, destFile) }) it("should move the file successfully when dest parent is 'src/dest_src'", () => { const destFile = path.join(TEST_DIR, 'src', 'dest_src', 'destfile.txt') return testSuccessFile(src, destFile) }) it("should move the file successfully when dest parent is 'src/dest/src'", () => { const destFile = path.join(TEST_DIR, 'src', 'dest', 'src', 'destfile.txt') return testSuccessFile(src, destFile) }) it("should move the file successfully when dest parent is 'srcsrc/dest'", () => { const destFile = path.join(TEST_DIR, 'srcsrc', 'dest', 'destfile.txt') return testSuccessFile(src, destFile) }) }) describe('> when source is a directory', () => { describe('>> when dest is a directory', () => { it('of not itself', () => { const dest = path.join(TEST_DIR, src.replace(/^\w:/, '')) return testSuccessDir(src, dest) }) it('of itself', () => { const dest = path.join(src, 'dest') return testError(src, dest) }) it("should move the directory successfully when dest is 'src_dest'", () => { const dest = path.join(TEST_DIR, 'src_dest') return testSuccessDir(src, dest) }) it("should move the directory successfully when dest is 'src-dest'", () => { const dest = path.join(TEST_DIR, 'src-dest') return testSuccessDir(src, dest) }) it("should move the directory successfully when dest is 'dest_src'", () => { const dest = path.join(TEST_DIR, 'dest_src') return testSuccessDir(src, dest) }) it("should move the directory successfully when dest is 'src_dest/src'", () => { const dest = path.join(TEST_DIR, 'src_dest', 'src') return testSuccessDir(src, dest) }) it("should move the directory successfully when dest is 'src-dest/src'", () => { const dest = path.join(TEST_DIR, 'src-dest', 'src') return testSuccessDir(src, dest) }) it("should move the directory successfully when dest is 'dest_src/src'", () => { const dest = path.join(TEST_DIR, 'dest_src', 'src') return testSuccessDir(src, dest) }) it("should move the directory successfully when dest is 'src_src/dest'", () => { const dest = path.join(TEST_DIR, 'src_src', 'dest') return testSuccessDir(src, dest) }) it("should move the directory successfully when dest is 'src-src/dest'", () => { const dest = path.join(TEST_DIR, 'src-src', 'dest') return testSuccessDir(src, dest) }) it("should move the directory successfully when dest is 'srcsrc/dest'", () => { const dest = path.join(TEST_DIR, 'srcsrc', 'dest') return testSuccessDir(src, dest) }) it("should move the directory successfully when dest is 'dest/src'", () => { const dest = path.join(TEST_DIR, 'dest', 'src') return testSuccessDir(src, dest) }) it('should move the directory successfully when dest is very nested that all its parents need to be created', () => { const dest = path.join(TEST_DIR, 'dest', 'src', 'foo', 'bar', 'baz', 'qux', 'quux', 'waldo', 'grault', 'garply', 'fred', 'plugh', 'thud', 'some', 'highly', 'deeply', 'badly', 'nasty', 'crazy', 'mad', 'nested', 'dest') return testSuccessDir(src, dest) }) it("should error when dest is 'src/dest'", () => { const dest = path.join(TEST_DIR, 'src', 'dest') return testError(src, dest) }) it("should error when dest is 'src/src_dest'", () => { const dest = path.join(TEST_DIR, 'src', 'src_dest') return testError(src, dest) }) it("should error when dest is 'src/dest_src'", () => { const dest = path.join(TEST_DIR, 'src', 'dest_src') return testError(src, dest) }) it("should error when dest is 'src/dest/src'", () => { const dest = path.join(TEST_DIR, 'src', 'dest', 'src') return testError(src, dest) }) }) describe('>> when dest is a symlink', () => { it('should error when dest points exactly to src and dereference is true', () => { const destLink = path.join(TEST_DIR, 'dest-symlink') fs.symlinkSync(src, destLink, 'dir') const srclenBefore = klawSync(src).length assert(srclenBefore > 2) let errThrown = false try { fs.moveSync(src, destLink, { dereference: true }) } catch (err) { assert.strictEqual(err.message, 'Source and destination must not be the same.') errThrown = true } finally { assert(errThrown) const srclenAfter = klawSync(src).length assert.strictEqual(srclenAfter, srclenBefore, 'src length should not change') const link = fs.readlinkSync(destLink) assert.strictEqual(link, src) } }) it('should error when dest is a subdirectory of src (bind-mounted directory with subdirectory)', () => { const destLink = path.join(TEST_DIR, 'dest-symlink') fs.symlinkSync(src, destLink, 'dir') const srclenBefore = klawSync(src).length assert(srclenBefore > 2) const dest = path.join(destLink, 'dir1') assert(fs.existsSync(dest)) let errThrown = false try { fs.moveSync(src, dest) } catch (err) { assert.strictEqual(err.message, `Cannot move '${src}' to a subdirectory of itself, '${dest}'.`) errThrown = true } finally { assert(errThrown) const srclenAfter = klawSync(src).length assert.strictEqual(srclenAfter, srclenBefore, 'src length should not change') const link = fs.readlinkSync(destLink) assert.strictEqual(link, src) } }) it('should error when dest is a subdirectory of src (more than one level depth)', () => { const destLink = path.join(TEST_DIR, 'dest-symlink') fs.symlinkSync(src, destLink, 'dir') const srclenBefore = klawSync(src).length assert(srclenBefore > 2) const dest = path.join(destLink, 'dir1', 'dir2') assert(fs.existsSync(dest)) let errThrown = false try { fs.moveSync(src, dest) } catch (err) { assert.strictEqual(err.message, `Cannot move '${src}' to a subdirectory of itself, '${path.join(destLink, 'dir1')}'.`) errThrown = true } finally { assert(errThrown) const srclenAfter = klawSync(src).length assert.strictEqual(srclenAfter, srclenBefore, 'src length should not change') const link = fs.readlinkSync(destLink) assert.strictEqual(link, src) } }) }) }) describe('> when source is a symlink', () => { describe('>> when dest is a directory', () => { it('should error when resolved src path points to dest', () => { const srcLink = path.join(TEST_DIR, 'src-symlink') fs.symlinkSync(src, srcLink, 'dir') const dest = path.join(TEST_DIR, 'src') let errThrown = false try { fs.moveSync(srcLink, dest) } catch (err) { assert(err) errThrown = true } finally { assert(errThrown) // assert source not affected const link = fs.readlinkSync(srcLink) assert.strictEqual(link, src) } }) it('should error when dest is a subdir of resolved src path', () => { const srcLink = path.join(TEST_DIR, 'src-symlink') fs.symlinkSync(src, srcLink, 'dir') const dest = path.join(TEST_DIR, 'src', 'some', 'nested', 'dest') fs.mkdirsSync(dest) let errThrown = false try { fs.moveSync(srcLink, dest) } catch (err) { assert(err) errThrown = true } finally { assert(errThrown) const link = fs.readlinkSync(srcLink) assert.strictEqual(link, src) } }) it('should error when resolved src path is a subdir of dest', () => { const dest = path.join(TEST_DIR, 'dest') const resolvedSrcPath = path.join(dest, 'contains', 'src') const srcLink = path.join(TEST_DIR, 'src-symlink') fs.copySync(src, resolvedSrcPath) // make symlink that points to a subdir in dest fs.symlinkSync(resolvedSrcPath, srcLink, 'dir') let errThrown = false try { fs.moveSync(srcLink, dest) } catch (err) { assert(err) errThrown = true } finally { assert(errThrown) } }) it("should move the directory successfully when dest is 'src_src/dest'", () => { const srcLink = path.join(TEST_DIR, 'src-symlink') fs.symlinkSync(src, srcLink, 'dir') const dest = path.join(TEST_DIR, 'src_src', 'dest') testSuccessDir(srcLink, dest) const link = fs.readlinkSync(dest) assert.strictEqual(link, src) }) it("should move the directory successfully when dest is 'srcsrc/dest'", () => { const srcLink = path.join(TEST_DIR, 'src-symlink') fs.symlinkSync(src, srcLink, 'dir') const dest = path.join(TEST_DIR, 'srcsrc', 'dest') testSuccessDir(srcLink, dest) const link = fs.readlinkSync(dest) assert.strictEqual(link, src) }) }) describe('>> when dest is a symlink', () => { it('should error when resolved dest path is exactly the same as resolved src path and dereferene is true', () => { const srcLink = path.join(TEST_DIR, 'src-symlink') fs.symlinkSync(src, srcLink, 'dir') const destLink = path.join(TEST_DIR, 'dest-symlink') fs.symlinkSync(src, destLink, 'dir') const srclenBefore = klawSync(srcLink).length const destlenBefore = klawSync(destLink).length assert(srclenBefore > 2) assert(destlenBefore > 2) let errThrown = false try { fs.moveSync(srcLink, destLink, { dereference: true }) } catch (err) { assert.strictEqual(err.message, 'Source and destination must not be the same.') errThrown = true } finally { assert(errThrown) const srclenAfter = klawSync(srcLink).length assert.strictEqual(srclenAfter, srclenBefore, 'src length should not change') const destlenAfter = klawSync(destLink).length assert.strictEqual(destlenAfter, destlenBefore, 'dest length should not change') const srcln = fs.readlinkSync(srcLink) assert.strictEqual(srcln, src) const destln = fs.readlinkSync(destLink) assert.strictEqual(destln, src) } }) }) }) }) function testSuccessFile (src, destFile) { const srcFile = path.join(src, FILES[0]) fs.moveSync(srcFile, destFile) const f0 = fs.readFileSync(destFile, 'utf8') assert.strictEqual(f0, dat0, 'file contents matched') assert(!fs.existsSync(srcFile)) } function testSuccessDir (src, dest) { const srclen = klawSync(src).length assert(srclen > 2) // assert src has contents fs.moveSync(src, dest) const destlen = klawSync(dest).length assert.strictEqual(destlen, srclen, 'src and dest length should be equal') const f0 = fs.readFileSync(path.join(dest, FILES[0]), 'utf8') const f1 = fs.readFileSync(path.join(dest, FILES[1]), 'utf8') const f2 = fs.readFileSync(path.join(dest, FILES[2]), 'utf8') const f3 = fs.readFileSync(path.join(dest, FILES[3]), 'utf8') assert.strictEqual(f0, dat0, 'file contents matched') assert.strictEqual(f1, dat1, 'file contents matched') assert.strictEqual(f2, dat2, 'file contents matched') assert.strictEqual(f3, dat3, 'file contents matched') assert(!fs.existsSync(src)) } function testError (src, dest) { let errThrown = false try { fs.moveSync(src, dest) } catch (err) { assert.strictEqual(err.message, `Cannot move '${src}' to a subdirectory of itself, '${dest}'.`) assert(fs.existsSync(src)) assert(!fs.existsSync(dest)) errThrown = true } finally { assert(errThrown) } } ================================================ FILE: lib/move/__tests__/move-sync.test.js ================================================ 'use strict' // TODO: enable this once graceful-fs supports bigint option. // const fs = require('graceful-fs') const fs = require('fs') const os = require('os') const fse = require('../..') const path = require('path') const assert = require('assert') const { differentDevice, ifCrossDeviceEnabled } = require('./cross-device-utils') /* global afterEach, beforeEach, describe, it */ const describeIfWindows = process.platform === 'win32' ? describe : describe.skip function createSyncErrFn (errCode) { const fn = function () { const err = new Error() err.code = errCode throw err } return fn } const originalRenameSync = fs.renameSync function setUpMockFs (errCode) { fs.renameSync = createSyncErrFn(errCode) } function tearDownMockFs () { fs.renameSync = originalRenameSync } describe('moveSync()', () => { let TEST_DIR beforeEach(() => { TEST_DIR = path.join(os.tmpdir(), 'fs-extra', 'move-sync') fse.emptyDirSync(TEST_DIR) // Create fixtures fse.outputFileSync(path.join(TEST_DIR, 'a-file'), 'sonic the hedgehog\n') fse.outputFileSync(path.join(TEST_DIR, 'a-folder/another-file'), 'tails\n') fse.outputFileSync(path.join(TEST_DIR, 'a-folder/another-folder/file3'), 'knuckles\n') }) afterEach(() => fse.removeSync(TEST_DIR)) it('should not move if src and dest are the same', () => { const src = `${TEST_DIR}/a-file` const dest = `${TEST_DIR}/a-file` let errThrown = false try { fse.moveSync(src, dest) } catch (err) { assert.strictEqual(err.message, 'Source and destination must not be the same.') errThrown = true } finally { assert(errThrown) } // assert src not affected const contents = fs.readFileSync(src, 'utf8') const expected = /^sonic the hedgehog\r?\n$/ assert(contents.match(expected)) }) it('should error if src and dest are the same and src does not exist', () => { const src = `${TEST_DIR}/non-existent` const dest = src assert.throws(() => fse.moveSync(src, dest)) }) it('should rename a file on the same device', () => { const src = `${TEST_DIR}/a-file` const dest = `${TEST_DIR}/a-file-dest` fse.moveSync(src, dest) const contents = fs.readFileSync(dest, 'utf8') const expected = /^sonic the hedgehog\r?\n$/ assert(contents.match(expected)) }) it('should not overwrite the destination by default', () => { const src = `${TEST_DIR}/a-file` const dest = `${TEST_DIR}/a-folder/another-file` // verify file exists already assert(fs.existsSync(dest)) try { fse.moveSync(src, dest) } catch (err) { assert.strictEqual(err.message, 'dest already exists.') } }) it('should not overwrite if overwrite = false', () => { const src = `${TEST_DIR}/a-file` const dest = `${TEST_DIR}/a-folder/another-file` // verify file exists already assert(fs.existsSync(dest)) try { fse.moveSync(src, dest, { overwrite: false }) } catch (err) { assert.strictEqual(err.message, 'dest already exists.') } }) it('should overwrite file if overwrite = true', () => { const src = `${TEST_DIR}/a-file` const dest = `${TEST_DIR}/a-folder/another-file` // verify file exists already assert(fs.existsSync(dest)) fse.moveSync(src, dest, { overwrite: true }) const contents = fs.readFileSync(dest, 'utf8') const expected = /^sonic the hedgehog\r?\n$/ assert.ok(contents.match(expected)) }) it('should overwrite the destination directory if overwrite = true', () => { // Create src const src = path.join(TEST_DIR, 'src') fse.ensureDirSync(src) fse.mkdirsSync(path.join(src, 'some-folder')) fs.writeFileSync(path.join(src, 'some-file'), 'hi') const dest = path.join(TEST_DIR, 'a-folder') // verify dest has stuff in it const pathsBefore = fs.readdirSync(dest) assert(pathsBefore.indexOf('another-file') >= 0) assert(pathsBefore.indexOf('another-folder') >= 0) fse.moveSync(src, dest, { overwrite: true }) // verify dest does not have old stuff const pathsAfter = fs.readdirSync(dest) assert.strictEqual(pathsAfter.indexOf('another-file'), -1) assert.strictEqual(pathsAfter.indexOf('another-folder'), -1) // verify dest has new stuff assert(pathsAfter.indexOf('some-file') >= 0) assert(pathsAfter.indexOf('some-folder') >= 0) }) it('should create directory structure by default', () => { const src = `${TEST_DIR}/a-file` const dest = `${TEST_DIR}/does/not/exist/a-file-dest` // verify dest directory does not exist assert(!fs.existsSync(path.dirname(dest))) fse.moveSync(src, dest) const contents = fs.readFileSync(dest, 'utf8') const expected = /^sonic the hedgehog\r?\n$/ assert(contents.match(expected)) }) it('should work across devices', () => { const src = `${TEST_DIR}/a-file` const dest = `${TEST_DIR}/a-file-dest` setUpMockFs('EXDEV') fse.moveSync(src, dest) const contents = fs.readFileSync(dest, 'utf8') const expected = /^sonic the hedgehog\r?\n$/ assert(contents.match(expected)) tearDownMockFs() }) it('should move folders', () => { const src = `${TEST_DIR}/a-folder` const dest = `${TEST_DIR}/a-folder-dest` // verify it doesn't exist assert(!fs.existsSync(dest)) fse.moveSync(src, dest) const contents = fs.readFileSync(dest + '/another-file', 'utf8') const expected = /^tails\r?\n$/ assert(contents.match(expected)) }) it('should overwrite folders across devices', () => { const src = `${TEST_DIR}/a-folder` const dest = `${TEST_DIR}/a-folder-dest` fs.mkdirSync(dest) setUpMockFs('EXDEV') fse.moveSync(src, dest, { overwrite: true }) const contents = fs.readFileSync(dest + '/another-folder/file3', 'utf8') const expected = /^knuckles\r?\n$/ assert(contents.match(expected)) tearDownMockFs() }) it('should move folders across devices with EXDEV error', () => { const src = `${TEST_DIR}/a-folder` const dest = `${TEST_DIR}/a-folder-dest` setUpMockFs('EXDEV') fse.moveSync(src, dest) const contents = fs.readFileSync(dest + '/another-folder/file3', 'utf8') const expected = /^knuckles\r?\n$/ assert(contents.match(expected)) tearDownMockFs() }) describe('clobber', () => { it('should be an alias for overwrite', () => { const src = `${TEST_DIR}/a-file` const dest = `${TEST_DIR}/a-folder/another-file` // verify file exists already assert(fs.existsSync(dest)) fse.moveSync(src, dest, { clobber: true }) const contents = fs.readFileSync(dest, 'utf8') const expected = /^sonic the hedgehog\r?\n$/ assert(contents.match(expected)) }) }) describe('> when trying to move a folder into itself', () => { it('should produce an error', () => { const SRC_DIR = path.join(TEST_DIR, 'src') const DEST_DIR = path.join(TEST_DIR, 'src', 'dest') assert(!fs.existsSync(SRC_DIR)) fs.mkdirSync(SRC_DIR) assert(fs.existsSync(SRC_DIR)) try { fse.moveSync(SRC_DIR, DEST_DIR) } catch (err) { assert(err.message, `Cannot move ${SRC_DIR} into itself ${DEST_DIR}.`) assert(fs.existsSync(SRC_DIR)) assert(!fs.existsSync(DEST_DIR)) } }) }) describe('> when trying to move a file into its parent subdirectory', () => { it('should move successfully', () => { const src = `${TEST_DIR}/a-file` const dest = `${TEST_DIR}/dest/a-file-dest` fse.moveSync(src, dest) const contents = fs.readFileSync(dest, 'utf8') const expected = /^sonic the hedgehog\r?\n$/ assert(contents.match(expected)) }) }) describeIfWindows('> when dest parent is root', () => { let dest afterEach(() => fse.removeSync(dest)) it('should not create parent directory', () => { const src = path.join(TEST_DIR, 'a-file') dest = path.join(path.parse(TEST_DIR).root, 'another-file') fse.moveSync(src, dest) const contents = fs.readFileSync(dest, 'utf8') const expected = /^sonic the hedgehog\r?\n$/ assert(contents.match(expected)) }) }) ifCrossDeviceEnabled(describe)('> when actually trying to move a folder across devices', () => { describe('> just the folder', () => { it('should move the folder', () => { const src = path.join(differentDevice, 'some/weird/dir-really-weird') const dest = path.join(TEST_DIR, 'device-weird') if (!fs.existsSync(src)) fse.mkdirpSync(src) assert(!fs.existsSync(dest)) assert(fs.lstatSync(src).isDirectory()) fse.moveSync(src, dest) assert(fs.existsSync(dest)) assert(fs.lstatSync(dest).isDirectory()) }) }) }) }) ================================================ FILE: lib/move/__tests__/move.test.js ================================================ 'use strict' const fs = require('../../fs') const os = require('os') const fse = require('../../') const path = require('path') const assert = require('assert') const { differentDevice, ifCrossDeviceEnabled } = require('./cross-device-utils') /* global afterEach, beforeEach, describe, it */ const describeIfWindows = process.platform === 'win32' ? describe : describe.skip function createAsyncErrFn (errCode) { async function fn () { fn.callCount++ const err = new Error() err.code = errCode return Promise.reject(err) } fn.callCount = 0 return fn } const originalRename = fs.rename function setUpMockFs (errCode) { fs.rename = createAsyncErrFn(errCode) } function tearDownMockFs () { fs.rename = originalRename } describe('+ move()', () => { let TEST_DIR beforeEach(() => { TEST_DIR = path.join(os.tmpdir(), 'fs-extra', 'move') fse.emptyDirSync(TEST_DIR) // Create fixtures: fs.writeFileSync(path.join(TEST_DIR, 'a-file'), 'sonic the hedgehog\n') fs.mkdirSync(path.join(TEST_DIR, 'a-folder')) fs.writeFileSync(path.join(TEST_DIR, 'a-folder/another-file'), 'tails\n') fs.mkdirSync(path.join(TEST_DIR, 'a-folder/another-folder')) fs.writeFileSync(path.join(TEST_DIR, 'a-folder/another-folder/file3'), 'knuckles\n') }) afterEach(done => fse.remove(TEST_DIR, done)) describe('> when overwrite = true', () => { it('should overwrite file', done => { const src = path.join(TEST_DIR, 'a-file') const dest = path.join(TEST_DIR, 'a-folder', 'another-file') // verify file exists already assert(fs.existsSync(dest)) fse.move(src, dest, { overwrite: true }, err => { assert.ifError(err) fs.readFile(dest, 'utf8', (err, contents) => { const expected = /^sonic the hedgehog\r?\n$/ assert.ifError(err) assert.ok(contents.match(expected)) done() }) }) }) it('should overwrite the destination directory', done => { // Create src const src = path.join(TEST_DIR, 'src') fse.ensureDirSync(src) fse.mkdirsSync(path.join(src, 'some-folder')) fs.writeFileSync(path.join(src, 'some-file'), 'hi') const dest = path.join(TEST_DIR, 'a-folder') // verify dest has stuff in it const paths = fs.readdirSync(dest) assert(paths.indexOf('another-file') >= 0) assert(paths.indexOf('another-folder') >= 0) fse.move(src, dest, { overwrite: true }, err => { assert.ifError(err) // verify dest does not have old stuff const paths = fs.readdirSync(dest) assert.strictEqual(paths.indexOf('another-file'), -1) assert.strictEqual(paths.indexOf('another-folder'), -1) // verify dest has new stuff assert(paths.indexOf('some-file') >= 0) assert(paths.indexOf('some-folder') >= 0) done() }) }) it('should overwrite folders across devices', done => { const src = path.join(TEST_DIR, 'a-folder') const dest = path.join(TEST_DIR, 'a-folder-dest') fs.mkdirSync(dest) setUpMockFs('EXDEV') fse.move(src, dest, { overwrite: true }, err => { assert.ifError(err) assert.strictEqual(fs.rename.callCount, 1) fs.readFile(path.join(dest, 'another-folder', 'file3'), 'utf8', (err, contents) => { const expected = /^knuckles\r?\n$/ assert.ifError(err) assert.ok(contents.match(expected)) tearDownMockFs() done() }) }) }) }) describe('> when overwrite = false', () => { it('should rename a file on the same device', done => { const src = path.join(TEST_DIR, 'a-file') const dest = path.join(TEST_DIR, 'a-file-dest') fse.move(src, dest, err => { assert.ifError(err) fs.readFile(dest, 'utf8', (err, contents) => { const expected = /^sonic the hedgehog\r?\n$/ assert.ifError(err) assert.ok(contents.match(expected)) done() }) }) }) it('should support promises', async () => { const src = path.join(TEST_DIR, 'a-file') const dest = path.join(TEST_DIR, 'a-file-dest') await fse.move(src, dest) const contents = fs.readFileSync(dest, 'utf8') const expected = /^sonic the hedgehog\r?\n$/ assert.ok(contents.match(expected)) }) it('should not move a file if source and destination are the same', done => { const src = path.join(TEST_DIR, 'a-file') const dest = src fse.move(src, dest, err => { assert.strictEqual(err.message, 'Source and destination must not be the same.') done() }) }) it('should error if source and destination are the same and source does not exist', done => { const src = path.join(TEST_DIR, 'non-existent') const dest = src fse.move(src, dest, err => { assert(err) done() }) }) it('should not move a directory if source and destination are the same', done => { const src = path.join(TEST_DIR, 'a-folder') const dest = src fse.move(src, dest, err => { assert.strictEqual(err.message, 'Source and destination must not be the same.') done() }) }) it('should not overwrite the destination by default', done => { const src = path.join(TEST_DIR, 'a-file') const dest = path.join(TEST_DIR, 'a-folder', 'another-file') // verify file exists already assert(fs.existsSync(dest)) fse.move(src, dest, err => { assert.strictEqual(err.message, 'dest already exists.') done() }) }) it('should not overwrite if overwrite = false', done => { const src = path.join(TEST_DIR, 'a-file') const dest = path.join(TEST_DIR, 'a-folder', 'another-file') // verify file exists already assert(fs.existsSync(dest)) fse.move(src, dest, { overwrite: false }, err => { assert.strictEqual(err.message, 'dest already exists.') done() }) }) it('should create directory structure by default', done => { const src = path.join(TEST_DIR, 'a-file') const dest = path.join(TEST_DIR, 'does', 'not', 'exist', 'a-file-dest') // verify dest directory does not exist assert(!fs.existsSync(path.dirname(dest))) fse.move(src, dest, err => { assert.ifError(err) fs.readFile(dest, 'utf8', (err, contents) => { const expected = /^sonic the hedgehog\r?\n$/ assert.ifError(err) assert.ok(contents.match(expected)) done() }) }) }) it('should work across devices', done => { const src = path.join(TEST_DIR, 'a-file') const dest = path.join(TEST_DIR, 'a-file-dest') setUpMockFs('EXDEV') fse.move(src, dest, err => { assert.ifError(err) assert.strictEqual(fs.rename.callCount, 1) fs.readFile(dest, 'utf8', (err, contents) => { const expected = /^sonic the hedgehog\r?\n$/ assert.ifError(err) assert.ok(contents.match(expected)) tearDownMockFs() done() }) }) }) it('should move folders', done => { const src = path.join(TEST_DIR, 'a-folder') const dest = path.join(TEST_DIR, 'a-folder-dest') // verify it doesn't exist assert(!fs.existsSync(dest)) fse.move(src, dest, err => { assert.ifError(err) fs.readFile(path.join(dest, 'another-file'), 'utf8', (err, contents) => { const expected = /^tails\r?\n$/ assert.ifError(err) assert.ok(contents.match(expected)) done() }) }) }) it('should move folders across devices with EXDEV error', done => { const src = path.join(TEST_DIR, 'a-folder') const dest = path.join(TEST_DIR, 'a-folder-dest') setUpMockFs('EXDEV') fse.move(src, dest, err => { assert.ifError(err) assert.strictEqual(fs.rename.callCount, 1) fs.readFile(path.join(dest, 'another-folder', 'file3'), 'utf8', (err, contents) => { const expected = /^knuckles\r?\n$/ assert.ifError(err) assert.ok(contents.match(expected)) tearDownMockFs() done() }) }) }) }) describe('> when opts is explicit undefined', () => { it('works with callbacks', done => { const src = path.join(TEST_DIR, 'a-file') const dest = path.join(TEST_DIR, 'a-file-dest') fse.move(src, dest, undefined, err => { assert.ifError(err) fs.readFile(dest, 'utf8', (err, contents) => { const expected = /^sonic the hedgehog\r?\n$/ assert.ifError(err) assert.ok(contents.match(expected)) done() }) }) }) it('works with promises', async () => { const src = path.join(TEST_DIR, 'a-file') const dest = path.join(TEST_DIR, 'a-file-dest') await fse.move(src, dest, undefined) const contents = fs.readFileSync(dest, 'utf8') const expected = /^sonic the hedgehog\r?\n$/ assert.ok(contents.match(expected)) }) }) describeIfWindows('> when dest parent is root', () => { let dest afterEach(done => fse.remove(dest, done)) it('should not create parent directory', done => { const src = path.join(TEST_DIR, 'a-file') dest = path.join(path.parse(TEST_DIR).root, 'another-file') fse.move(src, dest, err => { assert.ifError(err) fs.readFile(dest, 'utf8', (err, contents) => { const expected = /^sonic the hedgehog\r?\n$/ assert.ifError(err) assert.ok(contents.match(expected)) done() }) }) }) }) describe('> clobber', () => { it('should be an alias for overwrite', done => { const src = path.join(TEST_DIR, 'a-file') const dest = path.join(TEST_DIR, 'a-folder', 'another-file') // verify file exists already assert(fs.existsSync(dest)) fse.move(src, dest, { clobber: true }, err => { assert.ifError(err) fs.readFile(dest, 'utf8', (err, contents) => { const expected = /^sonic the hedgehog\r?\n$/ assert.ifError(err) assert.ok(contents.match(expected)) done() }) }) }) }) describe('> when trying to move a folder into itself', () => { it('should produce an error', done => { const SRC_DIR = path.join(TEST_DIR, 'test') const DEST_DIR = path.join(TEST_DIR, 'test', 'test') assert(!fs.existsSync(SRC_DIR)) fs.mkdirSync(SRC_DIR) assert(fs.existsSync(SRC_DIR)) fse.move(SRC_DIR, DEST_DIR, err => { assert(fs.existsSync(SRC_DIR)) assert.strictEqual(err.message, `Cannot move '${SRC_DIR}' to a subdirectory of itself, '${DEST_DIR}'.`) done() }) }) }) // tested on Linux ubuntu 3.13.0-32-generic #57-Ubuntu SMP i686 i686 GNU/Linux // this won't trigger a bug on Mac OS X Yosimite with a USB drive (/Volumes) // see issue #108 ifCrossDeviceEnabled(describe)('> when actually trying to move a folder across devices', () => { describe('>> just the folder', () => { it('should move the folder', done => { const src = path.join(differentDevice, 'some/weird/dir-really-weird') const dest = path.join(TEST_DIR, 'device-weird') if (!fs.existsSync(src)) { fse.mkdirpSync(src) } assert(!fs.existsSync(dest)) assert(fs.lstatSync(src).isDirectory()) fse.move(src, dest, err => { assert.ifError(err) assert(fs.existsSync(dest)) assert(fs.lstatSync(dest).isDirectory()) done() }) }) }) }) }) ================================================ FILE: lib/move/index.js ================================================ 'use strict' const u = require('universalify').fromPromise module.exports = { move: u(require('./move')), moveSync: require('./move-sync') } ================================================ FILE: lib/move/move-sync.js ================================================ 'use strict' const fs = require('graceful-fs') const path = require('path') const copySync = require('../copy').copySync const removeSync = require('../remove').removeSync const mkdirpSync = require('../mkdirs').mkdirpSync const stat = require('../util/stat') function moveSync (src, dest, opts) { opts = opts || {} const overwrite = opts.overwrite || opts.clobber || false const { srcStat, isChangingCase = false } = stat.checkPathsSync(src, dest, 'move', opts) stat.checkParentPathsSync(src, srcStat, dest, 'move') if (!isParentRoot(dest)) mkdirpSync(path.dirname(dest)) return doRename(src, dest, overwrite, isChangingCase) } function isParentRoot (dest) { const parent = path.dirname(dest) const parsedPath = path.parse(parent) return parsedPath.root === parent } function doRename (src, dest, overwrite, isChangingCase) { if (isChangingCase) return rename(src, dest, overwrite) if (overwrite) { removeSync(dest) return rename(src, dest, overwrite) } if (fs.existsSync(dest)) throw new Error('dest already exists.') return rename(src, dest, overwrite) } function rename (src, dest, overwrite) { try { fs.renameSync(src, dest) } catch (err) { if (err.code !== 'EXDEV') throw err return moveAcrossDevice(src, dest, overwrite) } } function moveAcrossDevice (src, dest, overwrite) { const opts = { overwrite, errorOnExist: true, preserveTimestamps: true } copySync(src, dest, opts) return removeSync(src) } module.exports = moveSync ================================================ FILE: lib/move/move.js ================================================ 'use strict' const fs = require('../fs') const path = require('path') const { copy } = require('../copy') const { remove } = require('../remove') const { mkdirp } = require('../mkdirs') const { pathExists } = require('../path-exists') const stat = require('../util/stat') async function move (src, dest, opts = {}) { const overwrite = opts.overwrite || opts.clobber || false const { srcStat, isChangingCase = false } = await stat.checkPaths(src, dest, 'move', opts) await stat.checkParentPaths(src, srcStat, dest, 'move') // If the parent of dest is not root, make sure it exists before proceeding const destParent = path.dirname(dest) const parsedParentPath = path.parse(destParent) if (parsedParentPath.root !== destParent) { await mkdirp(destParent) } return doRename(src, dest, overwrite, isChangingCase) } async function doRename (src, dest, overwrite, isChangingCase) { if (!isChangingCase) { if (overwrite) { await remove(dest) } else if (await pathExists(dest)) { throw new Error('dest already exists.') } } try { // Try w/ rename first, and try copy + remove if EXDEV await fs.rename(src, dest) } catch (err) { if (err.code !== 'EXDEV') { throw err } await moveAcrossDevice(src, dest, overwrite) } } async function moveAcrossDevice (src, dest, overwrite) { const opts = { overwrite, errorOnExist: true, preserveTimestamps: true } await copy(src, dest, opts) return remove(src) } module.exports = move ================================================ FILE: lib/output-file/__tests__/output.test.js ================================================ 'use strict' const fs = require('fs') const os = require('os') const fse = require('../..') const path = require('path') const assert = require('assert') /* global afterEach, beforeEach, describe, it */ describe('output', () => { let TEST_DIR beforeEach(done => { TEST_DIR = path.join(os.tmpdir(), 'fs-extra', 'output') fse.emptyDir(TEST_DIR, done) }) afterEach(done => fse.remove(TEST_DIR, done)) describe('+ outputFile', () => { describe('> when the file and directory does not exist', () => { it('should create the file', done => { const file = path.join(TEST_DIR, Math.random() + 't-ne', Math.random() + '.txt') assert(!fs.existsSync(file)) fse.outputFile(file, 'hi jp', err => { assert.ifError(err) assert(fs.existsSync(file)) assert.strictEqual(fs.readFileSync(file, 'utf8'), 'hi jp') done() }) }) it('should support promises', () => { const file = path.join(TEST_DIR, Math.random() + 't-ne', Math.random() + '.txt') assert(!fs.existsSync(file)) return fse.outputFile(file, 'hi jp') }) }) describe('> when the file does exist', () => { it('should still modify the file', done => { const file = path.join(TEST_DIR, Math.random() + 't-e', Math.random() + '.txt') fse.mkdirsSync(path.dirname(file)) fs.writeFileSync(file, 'hello world') fse.outputFile(file, 'hello jp', err => { if (err) return done(err) assert.strictEqual(fs.readFileSync(file, 'utf8'), 'hello jp') done() }) }) }) }) describe('+ outputFileSync', () => { describe('> when the file and directory does not exist', () => { it('should create the file', () => { const file = path.join(TEST_DIR, Math.random() + 'ts-ne', Math.random() + '.txt') assert(!fs.existsSync(file)) fse.outputFileSync(file, 'hello man') assert(fs.existsSync(file)) assert.strictEqual(fs.readFileSync(file, 'utf8'), 'hello man') }) }) describe('> when the file does exist', () => { it('should still modify the file', () => { const file = path.join(TEST_DIR, Math.random() + 'ts-e', Math.random() + '.txt') fse.mkdirsSync(path.dirname(file)) fs.writeFileSync(file, 'hello world') fse.outputFileSync(file, 'hello man') assert.strictEqual(fs.readFileSync(file, 'utf8'), 'hello man') }) }) }) }) ================================================ FILE: lib/output-file/index.js ================================================ 'use strict' const u = require('universalify').fromPromise const fs = require('../fs') const path = require('path') const mkdir = require('../mkdirs') const pathExists = require('../path-exists').pathExists async function outputFile (file, data, encoding = 'utf-8') { const dir = path.dirname(file) if (!(await pathExists(dir))) { await mkdir.mkdirs(dir) } return fs.writeFile(file, data, encoding) } function outputFileSync (file, ...args) { const dir = path.dirname(file) if (!fs.existsSync(dir)) { mkdir.mkdirsSync(dir) } fs.writeFileSync(file, ...args) } module.exports = { outputFile: u(outputFile), outputFileSync } ================================================ FILE: lib/path-exists/__tests__/path-exists-sync.test.js ================================================ 'use strict' /* eslint-env mocha */ const fs = require('../..') const path = require('path') const os = require('os') const assert = require('assert') describe('pathExists()', () => { let TEST_DIR beforeEach(done => { TEST_DIR = path.join(os.tmpdir(), 'fs-extra', 'path-exists') fs.emptyDir(TEST_DIR, done) }) afterEach(done => fs.remove(TEST_DIR, done)) it('should return false if file does not exist', () => { assert(!fs.pathExistsSync(path.join(TEST_DIR, 'somefile'))) }) it('should return true if file does exist', () => { const file = path.join(TEST_DIR, 'exists') fs.ensureFileSync(file) assert(fs.pathExistsSync(file)) }) }) ================================================ FILE: lib/path-exists/__tests__/path-exists.test.js ================================================ 'use strict' /* eslint-env mocha */ const fs = require('../..') const path = require('path') const os = require('os') const assert = require('assert') describe('pathExists()', () => { let TEST_DIR beforeEach(done => { TEST_DIR = path.join(os.tmpdir(), 'fs-extra', 'path-exists') fs.emptyDir(TEST_DIR, done) }) afterEach(done => fs.remove(TEST_DIR, done)) it('should return false if file does not exist', () => { return fs.pathExists(path.join(TEST_DIR, 'somefile')) .then(exists => assert(!exists)) }) it('should return true if file does exist', () => { const file = path.join(TEST_DIR, 'exists') fs.ensureFileSync(file) return fs.pathExists(file) .then(exists => assert(exists)) }) it('should pass an empty error parameter to the callback', done => { const file = path.join(TEST_DIR, 'exists') fs.ensureFileSync(file) fs.pathExists(file, (err, exists) => { assert.ifError(err) assert(exists) done() }) }) }) ================================================ FILE: lib/path-exists/index.js ================================================ 'use strict' const u = require('universalify').fromPromise const fs = require('../fs') function pathExists (path) { return fs.access(path).then(() => true).catch(() => false) } module.exports = { pathExists: u(pathExists), pathExistsSync: fs.existsSync } ================================================ FILE: lib/remove/__tests__/remove-dir.test.js ================================================ 'use strict' const fs = require('fs') const os = require('os') const fse = require('../..') const path = require('path') const assert = require('assert') /* global beforeEach, describe, it */ describe('remove / async / dir', () => { let TEST_DIR beforeEach(done => { TEST_DIR = path.join(os.tmpdir(), 'fs-extra', 'remove-async-dir') fse.emptyDir(TEST_DIR, done) }) describe('> when dir does not exist', () => { it('should not throw an error', done => { const someDir = path.join(TEST_DIR, 'some-dir/') assert.strictEqual(fs.existsSync(someDir), false) fse.remove(someDir, err => { assert.ifError(err) done() }) }) }) }) ================================================ FILE: lib/remove/__tests__/remove-file.test.js ================================================ // todo ================================================ FILE: lib/remove/__tests__/remove-sync-dir.test.js ================================================ 'use strict' const fs = require('fs') const os = require('os') const fse = require('../..') const path = require('path') const assert = require('assert') /* global beforeEach, describe, it */ describe('remove/sync', () => { let TEST_DIR beforeEach(done => { TEST_DIR = path.join(os.tmpdir(), 'fs-extra', 'remove-sync') fse.emptyDir(TEST_DIR, done) }) describe('+ removeSync()', () => { it('should delete directories and files synchronously', () => { assert(fs.existsSync(TEST_DIR)) fs.writeFileSync(path.join(TEST_DIR, 'somefile'), 'somedata') fse.removeSync(TEST_DIR) assert(!fs.existsSync(TEST_DIR)) }) it('should delete an empty directory synchronously', () => { assert(fs.existsSync(TEST_DIR)) fse.removeSync(TEST_DIR) assert(!fs.existsSync(TEST_DIR)) }) }) }) ================================================ FILE: lib/remove/__tests__/remove-sync-file.test.js ================================================ 'use strict' const fs = require('fs') const os = require('os') const fse = require('../..') const path = require('path') const assert = require('assert') /* global beforeEach, describe, it */ describe('remove/sync', () => { let TEST_DIR beforeEach(done => { TEST_DIR = path.join(os.tmpdir(), 'fs-extra', 'remove-sync') fse.emptyDir(TEST_DIR, done) }) describe('+ removeSync()', () => { it('should delete a file synchronously', () => { const file = path.join(TEST_DIR, 'file') fs.writeFileSync(file, 'hello') assert(fs.existsSync(file)) fse.removeSync(file) assert(!fs.existsSync(file)) }) }) }) ================================================ FILE: lib/remove/__tests__/remove.test.js ================================================ 'use strict' const assert = require('assert') const fs = require('fs') const os = require('os') const path = require('path') const randomBytes = require('crypto').randomBytes const fse = require('../..') /* global afterEach, beforeEach, describe, it */ let TEST_DIR function buildFixtureDir () { const buf = randomBytes(5) const baseDir = path.join(TEST_DIR, `TEST_fs-extra_remove-${Date.now()}`) fs.mkdirSync(baseDir) fs.writeFileSync(path.join(baseDir, Math.random() + ''), buf) fs.writeFileSync(path.join(baseDir, Math.random() + ''), buf) const subDir = path.join(TEST_DIR, Math.random() + '') fs.mkdirSync(subDir) fs.writeFileSync(path.join(subDir, Math.random() + ''), buf) return baseDir } describe('remove', () => { beforeEach(done => { TEST_DIR = path.join(os.tmpdir(), 'fs-extra', 'remove') fse.emptyDir(TEST_DIR, done) }) afterEach(done => fse.remove(TEST_DIR, done)) describe('+ remove()', () => { it('should delete an empty directory', done => { assert(fs.existsSync(TEST_DIR)) fse.remove(TEST_DIR, err => { assert.ifError(err) assert(!fs.existsSync(TEST_DIR)) done() }) }) it('should delete a directory full of directories and files', done => { buildFixtureDir() assert(fs.existsSync(TEST_DIR)) fse.remove(TEST_DIR, err => { assert.ifError(err) assert(!fs.existsSync(TEST_DIR)) done() }) }) it('should delete a file', done => { const file = path.join(TEST_DIR, 'file') fs.writeFileSync(file, 'hello') assert(fs.existsSync(file)) fse.remove(file, err => { assert.ifError(err) assert(!fs.existsSync(file)) done() }) }) it('should delete without a callback', done => { const file = path.join(TEST_DIR, 'file') fs.writeFileSync(file, 'hello') assert(fs.existsSync(file)) let existsChecker = setInterval(() => { fse.pathExists(file, (err, itDoes) => { assert.ifError(err) if (!itDoes && existsChecker) { clearInterval(existsChecker) existsChecker = null done() } }) }, 25) fse.remove(file) }) it('shouldn’t delete glob matches', function (done) { const file = path.join(TEST_DIR, 'file?') try { fs.writeFileSync(file, 'hello') } catch (ex) { if (ex.code === 'ENOENT') return this.skip('Windows does not support filenames with ‘?’ or ‘*’ in them.') throw ex } const wrongFile = path.join(TEST_DIR, 'file1') fs.writeFileSync(wrongFile, 'yo') assert(fs.existsSync(file)) assert(fs.existsSync(wrongFile)) fse.remove(file, err => { assert.ifError(err) assert(!fs.existsSync(file)) assert(fs.existsSync(wrongFile)) done() }) }) it('shouldn’t delete glob matches when file doesn’t exist', done => { const nonexistentFile = path.join(TEST_DIR, 'file?') const wrongFile = path.join(TEST_DIR, 'file1') fs.writeFileSync(wrongFile, 'yo') assert(!fs.existsSync(nonexistentFile)) assert(fs.existsSync(wrongFile)) fse.remove(nonexistentFile, err => { assert.ifError(err) assert(!fs.existsSync(nonexistentFile)) assert(fs.existsSync(wrongFile)) done() }) }) }) }) ================================================ FILE: lib/remove/index.js ================================================ 'use strict' const fs = require('graceful-fs') const u = require('universalify').fromCallback function remove (path, callback) { fs.rm(path, { recursive: true, force: true }, callback) } function removeSync (path) { fs.rmSync(path, { recursive: true, force: true }) } module.exports = { remove: u(remove), removeSync } ================================================ FILE: lib/util/__tests__/stat.test.js ================================================ 'use strict' const fs = require('../..') const os = require('os') const path = require('path') const assert = require('assert') const stat = require('../stat.js') /* global beforeEach, afterEach, describe, it */ describe('util/stat', () => { let TEST_DIR beforeEach(done => { TEST_DIR = path.join(os.tmpdir(), 'fs-extra', 'util-stat') fs.emptyDir(TEST_DIR, done) }) afterEach(done => fs.remove(TEST_DIR, done)) describe('should use stats with bigint type', () => { it('stat.checkPaths()', () => { const src = path.join(TEST_DIR, 'src') const dest = path.join(TEST_DIR, 'dest') fs.ensureFileSync(src) fs.ensureFileSync(dest) stat.checkPaths(src, dest, 'copy', {}, (err, stats) => { assert.ifError(err) assert.strictEqual(typeof stats.srcStat.ino, 'bigint') }) }) it('stat.checkPathsSync()', () => { const src = path.join(TEST_DIR, 'src') const dest = path.join(TEST_DIR, 'dest') fs.ensureFileSync(src) fs.ensureFileSync(dest) const { srcStat } = stat.checkPathsSync(src, dest, 'copy', {}) assert.strictEqual(typeof srcStat.ino, 'bigint') }) }) describe('should stop at src or root path and not throw max call stack size error', () => { it('stat.checkParentPaths()', () => { const src = path.join(TEST_DIR, 'src') let dest = path.join(TEST_DIR, 'dest') fs.ensureFileSync(src) fs.ensureFileSync(dest) dest = path.basename(dest) const srcStat = fs.statSync(src) stat.checkParentPaths(src, srcStat, dest, 'copy', err => { assert.ifError(err) }) }) it('stat.checkParentPathsSync()', () => { const src = path.join(TEST_DIR, 'src') let dest = path.join(TEST_DIR, 'dest') fs.ensureFileSync(src) fs.ensureFileSync(dest) dest = path.basename(dest) const srcStat = fs.statSync(src) stat.checkParentPathsSync(src, srcStat, dest, 'copy') }) }) describe('should get correct identical result when stat.ino or stat.dev is 0n', () => { it('stat.areIdentical', () => { assert.ok(stat.areIdentical({ ino: 0n, dev: 0n }, { ino: 0n, dev: 0n })) assert.ok(stat.areIdentical({ ino: 1n, dev: 0n }, { ino: 1n, dev: 0n })) assert.ok(stat.areIdentical({ ino: 0n, dev: 1n }, { ino: 0n, dev: 1n })) assert.ok(stat.areIdentical({ ino: 1n, dev: 1n }, { ino: 1n, dev: 1n })) assert.ok(!stat.areIdentical({ ino: 2n, dev: 0n }, { ino: 1n, dev: 0n })) assert.ok(!stat.areIdentical({ ino: 0n, dev: 2n }, { ino: 0n, dev: 1n })) assert.ok(!stat.areIdentical({ ino: 2n, dev: 1n }, { ino: 1n, dev: 2n })) }) }) }) ================================================ FILE: lib/util/__tests__/utimes.test.js ================================================ 'use strict' const fs = require('fs') const os = require('os') const fse = require('../..') const path = require('path') const assert = require('assert') const proxyquire = require('proxyquire') const u = require('universalify').fromCallback let gracefulFsStub let utimes /* global beforeEach, describe, it */ // HFS, ext{2,3}, FAT do not function hasMillisResSync () { let tmpfile = path.join('millis-test-sync' + Date.now().toString() + Math.random().toString().slice(2)) tmpfile = path.join(os.tmpdir(), tmpfile) // 550 millis past UNIX epoch const d = new Date(1435410243862) fs.writeFileSync(tmpfile, 'https://github.com/jprichardson/node-fs-extra/pull/141') const fd = fs.openSync(tmpfile, 'r+') fs.futimesSync(fd, d, d) fs.closeSync(fd) return fs.statSync(tmpfile).mtime > 1435410243000 } describe('utimes', () => { let TEST_DIR beforeEach(done => { TEST_DIR = path.join(os.tmpdir(), 'fs-extra', 'utimes') fse.emptyDir(TEST_DIR, done) // reset stubs gracefulFsStub = {} utimes = proxyquire('../utimes', { '../fs': gracefulFsStub }) }) describe('utimesMillis()', () => { // see discussion https://github.com/jprichardson/node-fs-extra/pull/141 it('should set the utimes w/ millisecond precision', done => { const tmpFile = path.join(TEST_DIR, 'someFile') fs.writeFileSync(tmpFile, 'hello') let stats = fs.lstatSync(tmpFile) // Apr 21st, 2012 const awhileAgo = new Date(1334990868773) const awhileAgoNoMillis = new Date(1334990868000) assert.notDeepStrictEqual(stats.mtime, awhileAgo) assert.notDeepStrictEqual(stats.atime, awhileAgo) utimes.utimesMillis(tmpFile, awhileAgo, awhileAgo, err => { assert.ifError(err) stats = fs.statSync(tmpFile) if (hasMillisResSync()) { assert.deepStrictEqual(stats.mtime, awhileAgo) assert.deepStrictEqual(stats.atime, awhileAgo) } else { assert.deepStrictEqual(stats.mtime, awhileAgoNoMillis) assert.deepStrictEqual(stats.atime, awhileAgoNoMillis) } done() }) }) it('should close open file desciptors after encountering an error', done => { const fakeFd = Math.random() gracefulFsStub.open = u((pathIgnored, flagsIgnored, modeIgnored, callback) => { if (typeof modeIgnored === 'function') callback = modeIgnored process.nextTick(() => callback(null, fakeFd)) }) let closeCalled = false gracefulFsStub.close = u((fd, callback) => { assert.strictEqual(fd, fakeFd) closeCalled = true if (callback) process.nextTick(callback) }) let testError gracefulFsStub.futimes = u((fd, atimeIgnored, mtimeIgnored, callback) => { process.nextTick(() => { testError = new Error('A test error') callback(testError) }) }) utimes.utimesMillis('ignored', 'ignored', 'ignored', err => { assert.strictEqual(err, testError) assert(closeCalled) done() }) }) }) }) ================================================ FILE: lib/util/async.js ================================================ 'use strict' // https://github.com/jprichardson/node-fs-extra/issues/1056 // Performing parallel operations on each item of an async iterator is // surprisingly hard; you need to have handlers in place to avoid getting an // UnhandledPromiseRejectionWarning. // NOTE: This function does not presently handle return values, only errors async function asyncIteratorConcurrentProcess (iterator, fn) { const promises = [] for await (const item of iterator) { promises.push( fn(item).then( () => null, (err) => err ?? new Error('unknown error') ) ) } await Promise.all( promises.map((promise) => promise.then((possibleErr) => { if (possibleErr !== null) throw possibleErr }) ) ) } module.exports = { asyncIteratorConcurrentProcess } ================================================ FILE: lib/util/stat.js ================================================ 'use strict' const fs = require('../fs') const path = require('path') const u = require('universalify').fromPromise function getStats (src, dest, opts) { const statFunc = opts.dereference ? (file) => fs.stat(file, { bigint: true }) : (file) => fs.lstat(file, { bigint: true }) return Promise.all([ statFunc(src), statFunc(dest).catch(err => { if (err.code === 'ENOENT') return null throw err }) ]).then(([srcStat, destStat]) => ({ srcStat, destStat })) } function getStatsSync (src, dest, opts) { let destStat const statFunc = opts.dereference ? (file) => fs.statSync(file, { bigint: true }) : (file) => fs.lstatSync(file, { bigint: true }) const srcStat = statFunc(src) try { destStat = statFunc(dest) } catch (err) { if (err.code === 'ENOENT') return { srcStat, destStat: null } throw err } return { srcStat, destStat } } async function checkPaths (src, dest, funcName, opts) { const { srcStat, destStat } = await getStats(src, dest, opts) if (destStat) { if (areIdentical(srcStat, destStat)) { const srcBaseName = path.basename(src) const destBaseName = path.basename(dest) if (funcName === 'move' && srcBaseName !== destBaseName && srcBaseName.toLowerCase() === destBaseName.toLowerCase()) { return { srcStat, destStat, isChangingCase: true } } throw new Error('Source and destination must not be the same.') } if (srcStat.isDirectory() && !destStat.isDirectory()) { throw new Error(`Cannot overwrite non-directory '${dest}' with directory '${src}'.`) } if (!srcStat.isDirectory() && destStat.isDirectory()) { throw new Error(`Cannot overwrite directory '${dest}' with non-directory '${src}'.`) } } if (srcStat.isDirectory() && isSrcSubdir(src, dest)) { throw new Error(errMsg(src, dest, funcName)) } return { srcStat, destStat } } function checkPathsSync (src, dest, funcName, opts) { const { srcStat, destStat } = getStatsSync(src, dest, opts) if (destStat) { if (areIdentical(srcStat, destStat)) { const srcBaseName = path.basename(src) const destBaseName = path.basename(dest) if (funcName === 'move' && srcBaseName !== destBaseName && srcBaseName.toLowerCase() === destBaseName.toLowerCase()) { return { srcStat, destStat, isChangingCase: true } } throw new Error('Source and destination must not be the same.') } if (srcStat.isDirectory() && !destStat.isDirectory()) { throw new Error(`Cannot overwrite non-directory '${dest}' with directory '${src}'.`) } if (!srcStat.isDirectory() && destStat.isDirectory()) { throw new Error(`Cannot overwrite directory '${dest}' with non-directory '${src}'.`) } } if (srcStat.isDirectory() && isSrcSubdir(src, dest)) { throw new Error(errMsg(src, dest, funcName)) } return { srcStat, destStat } } // recursively check if dest parent is a subdirectory of src. // It works for all file types including symlinks since it // checks the src and dest inodes. It starts from the deepest // parent and stops once it reaches the src parent or the root path. async function checkParentPaths (src, srcStat, dest, funcName) { const srcParent = path.resolve(path.dirname(src)) const destParent = path.resolve(path.dirname(dest)) if (destParent === srcParent || destParent === path.parse(destParent).root) return let destStat try { destStat = await fs.stat(destParent, { bigint: true }) } catch (err) { if (err.code === 'ENOENT') return throw err } if (areIdentical(srcStat, destStat)) { throw new Error(errMsg(src, dest, funcName)) } return checkParentPaths(src, srcStat, destParent, funcName) } function checkParentPathsSync (src, srcStat, dest, funcName) { const srcParent = path.resolve(path.dirname(src)) const destParent = path.resolve(path.dirname(dest)) if (destParent === srcParent || destParent === path.parse(destParent).root) return let destStat try { destStat = fs.statSync(destParent, { bigint: true }) } catch (err) { if (err.code === 'ENOENT') return throw err } if (areIdentical(srcStat, destStat)) { throw new Error(errMsg(src, dest, funcName)) } return checkParentPathsSync(src, srcStat, destParent, funcName) } function areIdentical (srcStat, destStat) { // stat.dev can be 0n on windows when node version >= 22.x.x return destStat.ino !== undefined && destStat.dev !== undefined && destStat.ino === srcStat.ino && destStat.dev === srcStat.dev } // return true if dest is a subdir of src, otherwise false. // It only checks the path strings. function isSrcSubdir (src, dest) { const srcArr = path.resolve(src).split(path.sep).filter(i => i) const destArr = path.resolve(dest).split(path.sep).filter(i => i) return srcArr.every((cur, i) => destArr[i] === cur) } function errMsg (src, dest, funcName) { return `Cannot ${funcName} '${src}' to a subdirectory of itself, '${dest}'.` } module.exports = { // checkPaths checkPaths: u(checkPaths), checkPathsSync, // checkParent checkParentPaths: u(checkParentPaths), checkParentPathsSync, // Misc isSrcSubdir, areIdentical } ================================================ FILE: lib/util/utimes.js ================================================ 'use strict' const fs = require('../fs') const u = require('universalify').fromPromise async function utimesMillis (path, atime, mtime) { // if (!HAS_MILLIS_RES) return fs.utimes(path, atime, mtime, callback) const fd = await fs.open(path, 'r+') let closeErr = null try { await fs.futimes(fd, atime, mtime) } finally { try { await fs.close(fd) } catch (e) { closeErr = e } } if (closeErr) { throw closeErr } } function utimesMillisSync (path, atime, mtime) { const fd = fs.openSync(path, 'r+') fs.futimesSync(fd, atime, mtime) return fs.closeSync(fd) } module.exports = { utimesMillis: u(utimesMillis), utimesMillisSync } ================================================ FILE: package.json ================================================ { "name": "fs-extra", "version": "11.3.4", "description": "fs-extra contains methods that aren't included in the vanilla Node.js fs package. Such as recursive mkdir, copy, and remove.", "engines": { "node": ">=14.14" }, "homepage": "https://github.com/jprichardson/node-fs-extra", "repository": { "type": "git", "url": "git+https://github.com/jprichardson/node-fs-extra.git" }, "keywords": [ "fs", "file", "file system", "copy", "directory", "extra", "mkdirp", "mkdir", "mkdirs", "recursive", "json", "read", "write", "extra", "delete", "remove", "touch", "create", "text", "output", "move", "promise" ], "author": "JP Richardson ", "license": "MIT", "dependencies": { "graceful-fs": "^4.2.0", "jsonfile": "^6.0.1", "universalify": "^2.0.0" }, "devDependencies": { "klaw": "^2.1.1", "klaw-sync": "^3.0.2", "minimist": "^1.1.1", "mocha": "^10.1.0", "nyc": "^15.0.0", "proxyquire": "^2.0.1", "read-dir-files": "^0.1.1", "standard": "^17.0.0" }, "main": "./lib/index.js", "exports": { ".": "./lib/index.js", "./esm": "./lib/esm.mjs" }, "files": [ "lib/", "!lib/**/__tests__/" ], "scripts": { "lint": "standard", "test-find": "find ./lib/**/__tests__ -name *.test.js | xargs mocha", "test": "npm run lint && npm run unit && npm run unit-esm", "unit": "nyc node test.js", "unit-esm": "node test.mjs" }, "sideEffects": false } ================================================ FILE: test/readme.md ================================================ Looking for the test files? You can find all of the test files in `lib/**/__tests__`. ================================================ FILE: test.js ================================================ 'use strict' const os = require('os') const path = require('path') const klaw = require('klaw') const Mocha = require('mocha') const argv = require('minimist')(process.argv.slice(2)) const mochaOpts = { ui: 'bdd', reporter: 'dot', timeout: 30000, ...argv } const mocha = new Mocha(mochaOpts) const testExt = '.test.js' klaw('./lib').on('readable', function () { let item while ((item = this.read())) { if (!item.stats.isFile()) return if (item.path.lastIndexOf(testExt) !== (item.path.length - testExt.length)) return mocha.addFile(item.path) } }).on('end', () => { mocha.run(failures => { require('./lib').remove(path.join(os.tmpdir(), 'fs-extra'), () => process.exit(failures)) }) }) ================================================ FILE: test.mjs ================================================ import assert from 'assert' import fsLegacy from './lib/index.js' // NOTE: eslint comments needed because we're importing the same file multiple times import fsDefault from './lib/esm.mjs' // eslint-disable-line import * as fsStar from './lib/esm.mjs' import { copy, copySync, emptyDirSync, emptydirSync, emptyDir, emptydir, createFile, createFileSync, ensureFile, ensureFileSync, createLink, createLinkSync, ensureLink, ensureLinkSync, createSymlink, createSymlinkSync, ensureSymlink, ensureSymlinkSync, readJson, readJsonSync, writeJson, writeJsonSync, outputJson, outputJsonSync, outputJSON, outputJSONSync, writeJSON, writeJSONSync, readJSON, readJSONSync, mkdirs, mkdirsSync, mkdirp, mkdirpSync, ensureDir, ensureDirSync, move, moveSync, outputFile, outputFileSync, pathExists, pathExistsSync, remove, removeSync } from './lib/esm.mjs' // eslint-disable-line const fsNamed = [ copy, copySync, emptyDirSync, emptydirSync, emptyDir, emptydir, createFile, createFileSync, ensureFile, ensureFileSync, createLink, createLinkSync, ensureLink, ensureLinkSync, createSymlink, createSymlinkSync, ensureSymlink, ensureSymlinkSync, readJson, readJsonSync, writeJson, writeJsonSync, outputJson, outputJsonSync, outputJSON, outputJSONSync, writeJSON, writeJSONSync, readJSON, readJSONSync, mkdirs, mkdirsSync, mkdirp, mkdirpSync, ensureDir, ensureDirSync, move, moveSync, outputFile, outputFileSync, pathExists, pathExistsSync, remove, removeSync ] const keys = Object.keys(fsDefault) assert.deepStrictEqual(Object.values(fsDefault), fsNamed, 'named and default exports should match') assert.deepStrictEqual( Object.entries(fsStar) .filter(([name]) => name !== 'default') // remove "default" property here .sort(([nameA], [nameB]) => keys.indexOf(nameA) - keys.indexOf(nameB)) // sort for exact match .map(([name, fn]) => fn), Object.values(fsDefault), 'star and default exports should match' ) // default exports a subset of the legacy implementation, but functions are the same Object.entries(fsDefault).forEach(([name, fn]) => { assert.strictEqual(fn, fsLegacy[name], `${name}() should match legacy implementation`) }) console.warn('ESM tests pass!')