Compare commits

..

448 Commits

Author SHA1 Message Date
dependabot[bot] 4f4015a4f7 chore(deps-dev): bump karma from 6.3.8 to 6.3.14
Bumps [karma](https://github.com/karma-runner/karma) from 6.3.8 to 6.3.14.
- [Release notes](https://github.com/karma-runner/karma/releases)
- [Changelog](https://github.com/karma-runner/karma/blob/master/CHANGELOG.md)
- [Commits](https://github.com/karma-runner/karma/compare/v6.3.8...v6.3.14)

---
updated-dependencies:
- dependency-name: karma
  dependency-type: direct:development
...

Signed-off-by: dependabot[bot] <support@github.com>
2022-02-11 11:38:38 -05:00
dependabot[bot] b73ce7bd2e chore(deps): bump log4js from 6.3.0 to 6.4.0
Bumps [log4js](https://github.com/log4js-node/log4js-node) from 6.3.0 to 6.4.0.
- [Release notes](https://github.com/log4js-node/log4js-node/releases)
- [Changelog](https://github.com/log4js-node/log4js-node/blob/master/CHANGELOG.md)
- [Commits](https://github.com/log4js-node/log4js-node/compare/v6.3.0...v6.4.0)

---
updated-dependencies:
- dependency-name: log4js
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2022-01-21 15:51:57 -05:00
David Humphrey 3279c2d65a Release 1.4.1 2021-11-15 18:13:39 -05:00
Ben Heidemann e135305f25
Fix Issue 790 and 791 (#795)
* fix: distribute shims and webpack folders to NPM

* docs: update README.md
2021-11-15 18:09:46 -05:00
David Humphrey 0b26979839 Release 1.4.0 2021-11-15 11:12:05 -05:00
Ben Heidemann 7efc4cdc1d
Fix Issue #790 (#793)
* fix: make wepback plugin available from filer/webpack

* deprecate accessing FilerWebpackPlugin through index.js

* docs: update documentation to reflect changes to FilerWebpackPlugin

* docs: fix typo
2021-11-15 11:05:39 -05:00
David Humphrey 4112d072b5 Release 1.3.1 2021-11-13 08:53:11 -05:00
David Humphrey ee26394ead Update dev deps 2021-11-13 08:48:53 -05:00
David Humphrey 9f8804f716 Update actions/setup-node to 2.4.1, fix matrix syntax 2021-10-19 16:58:00 -04:00
David Humphrey 621b6567e0 Update node matrix to 14, 16 2021-10-19 16:49:44 -04:00
David Humphrey 4acd064a2b Release 1.3.0 2021-10-19 16:44:10 -04:00
David Humphrey b283023286 Update deps 2021-10-19 16:40:38 -04:00
Arun Bose 24697a3ed9 fix: rename across directories working 2021-10-19 16:16:31 -04:00
dependabot[bot] 5f872f0f24 chore(deps): bump trim-newlines from 3.0.0 to 3.0.1
Bumps [trim-newlines](https://github.com/sindresorhus/trim-newlines) from 3.0.0 to 3.0.1.
- [Release notes](https://github.com/sindresorhus/trim-newlines/releases)
- [Commits](https://github.com/sindresorhus/trim-newlines/commits)

---
updated-dependencies:
- dependency-name: trim-newlines
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2021-06-08 11:10:49 -04:00
bcheidemann 77abca991a docs: format fs.readdir documentation section 2021-06-05 13:45:41 -04:00
bcheidemann 49ace4b2fb docs: add documentation for the options in fs.readdir 2021-06-05 13:45:41 -04:00
bcheidemann d055d8042e test: update tests for issue #775 2021-06-05 13:45:41 -04:00
bcheidemann 576831370f fix: handle withFileTypes options in readdir 2021-06-05 13:45:41 -04:00
bcheidemann 594ab2621f fix: mkdir accepts encoding options 2021-06-05 13:45:41 -04:00
Ben Heidemann 75a2cc86cf test: skip this until we have a fix 2021-06-05 13:45:41 -04:00
Ben Heidemann a4b3726520 test(#775): add regression test for issue #775 2021-06-05 13:45:41 -04:00
Ben Heidemann 21e7a4750a test: skip test for issue #776 until fix is finished 2021-05-26 09:55:26 -04:00
Ben Heidemann aa2df3a17c test(#776): add regression test for issue #776 2021-05-26 09:55:26 -04:00
Ben Heidemann bd15462f6e test: skip test for issue #776 until fix is finished 2021-05-26 09:55:26 -04:00
Ben Heidemann 78ae19fbad test(#776): add regression test for issue #776 2021-05-26 09:55:26 -04:00
Ben Heidemann b3caddcfec refactor: make fs shim a commonjs module to match node.js fs module 2021-05-26 09:54:38 -04:00
Ben Heidemann 11e05e131b fix: make fs proxy return undefined for keys which do not exist on the file system instance 2021-05-26 09:54:38 -04:00
Ben Heidemann fb100b165a refactor: use Object.assign instead of Object.create for cloning nodePath
because Object.keys omits many of the methods on the filerPath module when using Object.create
2021-05-26 09:54:38 -04:00
Ben Heidemann e94543471b test: rename webpack plugin test 2021-05-26 09:54:38 -04:00
Ben Heidemann 20d4d5e720 chore: remove path dependency 2021-05-26 09:54:38 -04:00
Ben Heidemann 0295d19a7f refactor: rename plugin.js to index.js 2021-05-26 09:54:38 -04:00
Ben Heidemann 365a7d23a3 test: remove describe.only 2021-05-26 09:54:38 -04:00
Ben Heidemann ea5e48b48b style: fix linting issues 2021-05-26 09:54:38 -04:00
Ben Heidemann e82374ae2b test: add spec for webpack plugin 2021-05-26 09:54:38 -04:00
Ben Heidemann 5bd05287d4 test: add mock function create helper to utils 2021-05-26 09:54:38 -04:00
Ben Heidemann 1c34abf009 style: add missing indents in switch 2021-05-26 09:54:38 -04:00
Ben Heidemann 8b4b0a6140 fix: when cwd is root and the <rootDir> tag is replaced, the resulting path should not begin with // 2021-05-26 09:54:38 -04:00
Ben Heidemann e489409b9c test: remove buffer shim spec test 2021-05-26 09:54:38 -04:00
Ben Heidemann 0db08e31bb docs: remove buffer shim docs and replace with info on why it's not provided 2021-05-26 09:54:38 -04:00
Ben Heidemann 1f02edf5b3 refactor: remove buffer shim option from filer webpack plugin 2021-05-26 09:54:38 -04:00
Ben Heidemann 708c84fc63 refactor: remove buffer shim 2021-05-26 09:54:38 -04:00
Ben Heidemann 4e45701b51 test: update path shim test to not use broken import 2021-05-26 09:54:38 -04:00
Ben Heidemann fe9ed6a648 fix: fix shim path export 2021-05-26 09:54:38 -04:00
Ben Heidemann 81ab65b95c docs: update and replace README.md section on using regular node.js imports 2021-05-26 09:54:38 -04:00
Ben Heidemann 582352f754 refactor: add missing import for path in processors 2021-05-26 09:54:38 -04:00
Ben Heidemann 3b9fafc53e style: fix linting issues in webpack plugin 2021-05-26 09:54:38 -04:00
Ben Heidemann bfb50bf608 docs: fix typo in README.md 2021-05-26 09:54:38 -04:00
Ben Heidemann ce56539190 docs: fix typo in webpack plugin docs 2021-05-26 09:54:38 -04:00
Ben Heidemann 0f812fc6a0 refactor: remove typo in webpack plugin 2021-05-26 09:54:38 -04:00
Ben Heidemann 767c83706b docs: add missing filer import in webpack.config.js code snippet 2021-05-26 09:54:38 -04:00
Ben Heidemann 6a20ac2c3f docs: replace alias documentation with docs for FilerWebpackPlugin 2021-05-26 09:54:38 -04:00
Ben Heidemann 2bcf7e560b refactor: export filer webpack plugin in index.js 2021-05-26 09:54:38 -04:00
Ben Heidemann d040763a73 feat: add filer webpack plugin 2021-05-26 09:54:38 -04:00
Ben Heidemann fd90f32d4c chore: add path and schema-utils as dependancies 2021-05-26 09:54:38 -04:00
dependabot[bot] e18104a60d chore(deps): bump browserslist from 4.11.1 to 4.16.6
Bumps [browserslist](https://github.com/browserslist/browserslist) from 4.11.1 to 4.16.6.
- [Release notes](https://github.com/browserslist/browserslist/releases)
- [Changelog](https://github.com/browserslist/browserslist/blob/main/CHANGELOG.md)
- [Commits](https://github.com/browserslist/browserslist/compare/4.11.1...4.16.6)

Signed-off-by: dependabot[bot] <support@github.com>
2021-05-26 09:46:18 -04:00
Ben Heidemann 7bd6e5f4e1 fix: handle case data = 0 in writeFile 2021-04-18 11:44:39 -04:00
Ben Heidemann 90db749ee5 fix: handle case data = 0 in writeFile 2021-04-18 11:44:39 -04:00
Ben Heidemann f9c5473c49 test: add missing space in issue 773 regression test 2021-04-18 11:44:39 -04:00
Ben Heidemann f5ad682fd7 fix: allow encodings other that utf8 when using writeFile 2021-04-18 11:44:39 -04:00
Ben Heidemann 7b1c3e85ce fix(#773): use utf8 encoding when reading file when encoding not specified by options 2021-04-18 11:44:39 -04:00
Ben Heidemann 51afeeaf54 test: simplify regression test for issue773 2021-04-18 11:44:39 -04:00
Ben Heidemann cef6adfc37 style: fix linting issues and invoke done with error if error is captured 2021-04-18 11:44:39 -04:00
Ben Heidemann 6590cb79bd test: add regression test for issue 773 2021-04-18 11:44:39 -04:00
Ben Heidemann 3e88aeca92
Fix issue #766: Remove describe.only from shim tests (#767)
* test: replace describe.only in shim tests with describes so all tests run

* test: move require chai to top of file for consistency with other tests

* chore: npm install

* test: replace describe.only in shim tests with describes so all tests run

* test: move require chai to top of file for consistency with other tests

* chore: npm install

* Revert "chore: npm install"

This reverts commit cddeef421b.

* Revert "test: move require chai to top of file for consistency with other tests"

This reverts commit 40df7912fb.
2021-03-21 13:57:34 -04:00
Ben Heidemann f8c9732be9 docs: correct error in buffer shim documentation 2021-03-20 11:54:36 -04:00
David Humphrey 200171d2a5 Use node-version vs. node_version 2021-03-20 11:48:00 -04:00
David Humphrey 095f78498f Change node version definition in node-js-ci 2021-03-20 11:39:37 -04:00
David Humphrey 5cf2495079 Update node-js-ci workflow to fix broken npm installs 2021-03-20 11:32:38 -04:00
David Humphrey aacc8061cf
Merge pull request #762 from medayo/resolvePackageJSONConflicts
Using filer with webpack
2021-03-07 10:53:40 -05:00
Ben Heidemann c378288819
Merge branch 'master' into resolvePackageJSONConflicts 2021-03-07 15:36:28 +00:00
Ben Heidemann d1054753a6
Merge pull request #3 from medayo/fixTypo
docs: fix buffer import example in README.md
2021-03-07 15:26:31 +00:00
bcheidemann 887ed9318a docs: fix buffer import example in README.md 2021-03-07 15:25:52 +00:00
Ben Heidemann ce076729f6
Merge pull request #2 from medayo/shimTests
Shim tests and buffer shim/docs
2021-03-07 15:23:45 +00:00
bcheidemann a2151cab25 test: add spec for path shim 2021-03-07 15:21:39 +00:00
bcheidemann 3a8a59d362 test: add spec for buffer shim 2021-03-07 15:21:28 +00:00
bcheidemann 15be384940 test: run tests for path and buffer 2021-03-07 15:21:11 +00:00
bcheidemann 6027376efa refactor: use correct import for Buffer in buffer shim 2021-03-07 15:20:58 +00:00
bcheidemann 8b57d299f4 test: add test for fs shim 2021-03-07 15:05:18 +00:00
bcheidemann d6b29226aa refactor: return result of fn when wrapping in utils.shimIndexDB 2021-03-07 15:02:29 +00:00
bcheidemann da65e06e3c test: run fs shim spec test 2021-03-07 15:01:51 +00:00
bcheidemann aa152955b5 refactor: use correct path import in shim 2021-03-07 15:01:05 +00:00
bcheidemann d264113e0d docs: add documentation for use of buffer shim to README.md 2021-03-07 14:58:35 +00:00
bcheidemann ce809c4ac9 feat: add buffer shim 2021-03-07 14:58:09 +00:00
dependabot[bot] 3061328459 Bump ini from 1.3.5 to 1.3.8
Bumps [ini](https://github.com/isaacs/ini) from 1.3.5 to 1.3.8.
- [Release notes](https://github.com/isaacs/ini/releases)
- [Commits](https://github.com/isaacs/ini/compare/v1.3.5...v1.3.8)

Signed-off-by: dependabot[bot] <support@github.com>
2021-02-24 15:24:13 -05:00
David Humphrey c0a41d67ff Add .gitattributes and define eol style as lf 2021-02-24 12:35:38 -05:00
David Humphrey 4941d10e13 Remove 16.x from GitHub Actions node build matrix 2021-02-24 12:07:57 -05:00
David Humphrey 07a00a3f77 Update deps, add GitHub Actions CI 2021-02-24 12:04:39 -05:00
bcheidemann 0f5fe64ae8 chore: npm install regenerator-runtime 2021-02-21 10:25:43 +00:00
bcheidemann 7ec1fed51f chore: use regenerator runtime in tests for async/await 2021-02-21 10:21:03 +00:00
bcheidemann a2f7ee044b chore: show console logs when running tests 2021-02-21 10:18:57 +00:00
bcheidemann 7415e45867 docs: fix typo in README.md
replace 'alternative file sytem' with 'alternative file system provider'
2021-02-21 00:24:19 +00:00
bcheidemann 986ad37597 refactor: get reference to error in catch block
fixes red squigle for unexpected {
2021-02-21 00:21:20 +00:00
bcheidemann 9c669564b2 refactor: change fsprovider to fsProvider 2021-02-21 00:19:17 +00:00
bcheidemann 9d03788c1c docs: add own name to authors file 2021-02-20 04:14:24 +00:00
Ben Heidemann a60d2b4cfc
Merge pull request #1 from medayo/feat/shims
Feat/shims
2021-02-20 04:09:06 +00:00
bcheidemann 417a4e97dd docs: 2021-02-20 04:04:37 +00:00
bcheidemann 4d4b6bf3f3 docs: add recommendation to use fsprovider alias in README.md 2021-02-20 03:54:01 +00:00
bcheidemann f12f01dca0 feat: add path shim 2021-02-20 03:38:52 +00:00
bcheidemann 128e10dc13 docs: add webpack section to README.md 2021-02-20 03:36:34 +00:00
bcheidemann ceed84f377 feat: add shim for fs 2021-02-20 02:43:21 +00:00
bcheidemann 2a581726c6 feat: add shims for file system providers 2021-02-20 02:38:43 +00:00
David Humphrey 75f2a70c7b Fix tag and release naming for release-it update 2020-04-13 13:03:11 -04:00
David Humphrey 9db879374d Release 1.2.0 2020-04-13 12:55:50 -04:00
David Humphrey 98683fe261 Update deps, fix new eslint issues, update release-it config 2020-04-13 12:32:17 -04:00
SillyFreak f1fc53d88f resolve relative paths, add two test cases 2020-04-13 11:49:46 -04:00
Rachael Scotchmer 4aae53839a Issue 627 (#746)
* added test to fs.readlink.spec.js

* added test for fs.write() to try and write a file opened without the O_WRITE flag

* added test to fs.write() that attempts to write with a buffer that is too small

* added a test to fs.write() to try and write to a file that doesn't exist

* added more specific summary of test for writing to buffer when length is too long, check the type of error that a test returns

* Adjusted the message on line 69 to be more clear
2019-03-12 15:12:38 -04:00
dcoull 94d5ff8795 Addressed Issue #703 (#711)
* update from var to let and const

* Update from var to let and const

* Update times.spec.js from var to let and const

* Strict mode addition, migrated let usage to const

* Revert changes to package-lock.json
2019-03-05 15:46:23 -05:00
Charles M Drani ee56794601 add test for fs.open with wx flag for existing file (#745)
* add test for fs.open with wx flag for existing file

* update implementation and open spec to throw EEXIST
2019-02-27 11:56:11 -05:00
rscotchmer 914ba8b473 added test to fs.readlink.spec.js 2019-02-26 12:06:41 -05:00
Oleksii Polovyi 2a4fa0f0fd fixed #738: consolidated stats into stat tests (#743)
* fixed #738: consolidated stats into stat tests

* fix for newline and import spacing
2019-02-23 16:42:51 -05:00
ApolllonDev 9d3f220d92 increase test timeout to 10 seconds from 5 seconds 2019-02-23 16:42:03 -05:00
Abdirahman Guled 3d10d6431c Fix #710: updated let to const. 2019-02-15 15:04:04 -05:00
Adel El Masery 7ab6f5e7c6 Update fs.read.spec.js (#741)
* Update fs.read.spec.js

* Update fs.read.spec.js
2019-02-12 16:44:21 -05:00
kwchan19 9487e8ecc6 Issue 728: Updated 'filer/tests/spec/fs.shell.spec.js' to use 'const/let' instead of 'var' (#730)
* Fixes for review comments

* Fixes for review comments

* Fixes for review comments

* Fixes for review comments

* Fixes for review comments
2019-02-12 14:50:57 -05:00
hoaianhkhang e6f8ef2251 Issue #715 Update fs.lstat.spec.js to have proper const and let instead of var and added 'use strict' (#727)
* Update fs.lstat.spec.js

* Update fs.lstat.spec.js

* Update fs.lstat.spec.js

* Update fs.lstat.spec.js

* Update fs.lstat.spec.js

* Update fs.lstat.spec.js

* Update fs.lstat.spec.js
2019-02-12 14:49:20 -05:00
Paul Moon f2201e7a74 Update fs.spec.js to use strict mode and changed var to let (#693)
* Update fs.spec.js

* Update fs.spec.js

Changed global variables

* Update fs.spec.js

changed let to const
2019-02-12 14:46:56 -05:00
otkach 3447ec9c8a Updated file for issue #714 (#732)
* Updated file for issue 714

* Updated file due to review requirements
2019-02-08 15:00:45 -05:00
David Humphrey (:humph) david.humphrey@senecacollege.ca fe17870a8f Merge branch 'issue-734' 2019-02-08 14:52:57 -05:00
David Humphrey f4e0dce8d3
Merge pull request #733 from PriyankaCodes99/issue-685
issue-685 fix: replaced "var" with "let" in fs.unlink.spec.js
2019-02-08 14:42:53 -05:00
Priyanka Dhiman 34e5580a66 changes made as requested 2019-02-08 11:32:27 -05:00
Aqeel Parpia c515865fb3 [Issue 734] 2019-02-08 05:46:54 -05:00
Aqeel Parpia 4887cc725f issue 734 2019-02-08 05:36:55 -05:00
Aqeel Parpia 3471848b39 [issue-734] 2019-02-08 05:25:26 -05:00
David Humphrey 9b3e567dd1 Release 1.1.2 2019-02-07 22:54:40 -05:00
David Humphrey bf18093661 fs.lstat should return a Stats object including mode 2019-02-07 22:51:52 -05:00
David Humphrey fa3186d322 Release 1.1.1 2019-02-07 16:38:32 -05:00
David Humphrey 8a2e64f9ea Fix #736: use ms vs. s resolution on all times 2019-02-07 16:36:17 -05:00
Alvin Valdez 0ec51a198d Fix for issue-670: Changed var to const (#687)
* Changed var to const

* Added 'use strict' to top of file

* Update stats.js

* Update stats.js
2019-02-05 14:38:59 -05:00
Oleksii Polovyi 317cee5636 Fix issue #672 : Refactor "filer/tests/spec/fs.mkdir.spec.js" to follow ES6 syntax with "const/let" instead of "var" (#722)
* Solution for issue-672

* Removed extra 'use strict';
2019-02-05 14:20:48 -05:00
cmchumak 3c51bbb24f Issue-686 - rfs.mkdtemp.spec.js (#717)
* Replaced 'var' with 'const' where applicable

* Issue-686 - replacing 'var' with 'const', added 'use strict' fs.mkdtemp.spec.js

*  Issue-686 - replacing 'var' with 'const', updated 'use strict' fs.mkdtemp.spec.js
2019-02-05 13:58:01 -05:00
Arash N 9d4b264479 Update errors.spec.js (#718)
* Update errors.spec.js

Updating errors.spec.js to use const/let appropriately instead of var.

* Update errors.spec.js

- Changed corrected 'using' to 'use'.
- Changed 'let' to 'const' becuase the're not being changed during the function scope.
2019-02-05 13:51:29 -05:00
Sahib Arora b5e1d9a82b 'Use strict' @top and updated the file with const/let [issue-702] (#726)
* filer.spec.js var changed to const/let

* let changed to const for a local variable, which is constant through out
2019-02-05 13:46:58 -05:00
Jacob Adach da1aad5667 fixes issue #667 (#678)
* fixes issue 667: Update code in tests/some/fs.write.spec.js to use const/let AND strict mode

* fixes issue 667: Update code in tests/some/fs.write.spec.js to use const/let AND strict mode

* changed let to const for variables pointing to required function

* switched a few variable lets to const in file fs.write.spec.js

* switched a few variable lets to const in file fs.write.spec.js

* added package-lock.json file

* changed variables let to const
2019-02-01 20:53:12 -05:00
Violet-XiaoWeiHuang 05057c45d2 Fix ssue #692: Update code in filer/tests/spec/time-flags.spec.js (#696)
* installed npm

* modified time-flags.spec.js

* Update code to use const/let instead of var

* update the variable type from let to const

* add Strict mode

* review fixed
2019-02-01 15:04:15 -05:00
Rachael Scotchmer 4ba9eded4c Fix Issue 684: Replace var with const, let in filer/tests/spec/filer.buffer.spec.js (#697)
* refactored code in tests/spec/filer.buffer.spec.js

* reverted changes to package-lock.json which shouldn't have been changed

* updated package-lock.json

* trying to fix bug

* roll back changes to package-lock.json, change lets to consts in filer.buffer.spec.js, added new line at the end of filer.buffer.spec.js
2019-02-01 12:45:54 -05:00
Woosle Park 8eaaeeed17 Fix issue #681: Updated filer/tests/spec/filer.filesystem.spec.js (#695)
* issue 681 fix

* issue 681 revision

* issue 681 revision v2
2019-01-31 20:23:57 -05:00
Brandon Wissmann 3b4bf42604 Fixes #662: exchange var for const of require statements in src/filesystem/interface.js (#668)
* exchange var for const of require statements

Changed decleration of import files from var to const in interface.js

* Fixed all areas where var was used as well as use destructing assignment for  CONST imports.

* Fixed import const statement

* Added changes from let to const in certain lines
2019-01-31 20:22:46 -05:00
Harsh Patel 701849eb5a Fixed #707 Replaced var with const and let and added strict mode (#712)
* Fixed #707 Replaced var with const and let and added strict mode

* Fixed src/fs-watcher.js and changed remaining var to let

* Changed src/fs-watcher.js file to use const instead of let at line 52 and 57
2019-01-31 20:20:56 -05:00
DavidLi119 87513997a2 Fixed #708: Added 'use strict' and replaced var with let/const in fs.appendFile.spec.js (#713)
* Add files via upload

* Add files via upload

* Revert "Add files via upload"

This reverts commit 214977d8bf.

* Update fs.appendFile.spec.js

* s

* Revert "s"

This reverts commit 8aa5cbbbd6.

* Changed all `let` to `const`

As informed, all variables will not change at all in this file, therefore all `let` declarations have been changed to `const`
2019-01-31 18:42:50 -05:00
bonbon12 1e660a9d07 Fixed #699 Replacing var with let/const and adding strict mode (#706)
* Updated File to use let/const and strict mode

* Update path-resolution.spec.js

* Updated path-resolution.spec.js

Upon review and further inspection, there was a realization that there was need for the "let" variable as all variable were not modified.
Instead, "const" was used.
2019-01-31 16:42:38 -05:00
Iryna Thompson 3f619fdcb8 Fixed #665: Replaced var with let or const and added strict mode fs.a… (#688)
* Fixed #665: Replaced var with let or const and added strict mode fs.access.spec.js

* Replaced let with const

* Replaced all let with const
2019-01-31 16:08:19 -05:00
Vincent Logozzo 43bba422d9 fixed Issue-689 indexedDB.js (#700)
* CRLF replaced with LF

* package changes to run tests

* updated local varriables to use let and const instead of var

* reverted dependency changes
2019-01-31 15:40:09 -05:00
Priyam Brahmbhatt 7e46fcde8f updated environment.js to use const insted of var for constant property (#709)
* updated environment.js to use const insted of var for constant property

* Added use strict
2019-01-31 15:32:57 -05:00
OlenaVyshnevska fc545ee3c7 code refactoring, added strict mode (#704) 2019-01-31 15:25:57 -05:00
Yuansheng Lu e5481efa9b Fix issue #660: Updated the code to replace var with let, const in strict mode (#694)
* Modify the test file to fix issue-660

* change let to const
2019-01-31 15:11:07 -05:00
Vladimir Rozin 5918cf6ae7 changed fs.watch.spec.js according to filed issue-666 (#680) 2019-01-31 14:12:08 -05:00
jatinkumar 0380a8153c Fixed #667: Replaced var with const and added strict mode in fs.readdir.spec.js (#675)
* Replaced var with either const or let and added strict mode in fs.readdir.spec.js

* Replaced let with const
2019-01-31 14:07:31 -05:00
Nathaniel Ngo 4a39dcc2f0 Fixes Issue#674: Refactored var declarations to const or let declarations to address i… (#676)
* Refactored var declarations to const or let declarations to address issue#674

* refactored let to const when variable does not change values
2019-01-31 14:00:48 -05:00
andrewkoung 4de0bbfafd Fixes #661: replaced var with const (#669)
* replaced var with const for the most part

* Update fs.symlink.spec.js

fixed line 93 and added strict mode
2019-01-31 13:52:39 -05:00
Priyanka Dhiman 7cdef6d963 replaced var with let 2019-01-30 22:27:11 -05:00
David Humphrey 26b47ee094
Remove src/encodings.js, use Buffer methods instead (#657) 2019-01-03 10:46:31 -05:00
David Humphrey 5f10cc2fde Add test API to shim indexedDB when necessary for better coverage 2019-01-03 00:08:22 -05:00
David Humphrey 4e9593f5e8 Bump license date to reflect 2019 activity 2019-01-02 23:20:41 -05:00
David Humphrey 01d76ba0df Update keywords to remove WebSQL 2019-01-02 23:20:19 -05:00
David Humphrey dd7536827b Release 1.1.0 2019-01-02 23:12:19 -05:00
David Humphrey c6e1d51612 Reorder method order to match node's lib/fs.js, document missing 2019-01-02 23:09:47 -05:00
David Humphrey c0acdb97d6 Match node's layout for access modes on fs, with tests 2019-01-02 22:23:58 -05:00
David Humphrey f4ff2e9ed9
Add Filer.fs to support creating a filesystem like node.js (#651)
* Add Filer.fs to support

* Update README code examples, add tests, also expose Path as path
2019-01-02 21:21:25 -05:00
David Humphrey (:humph) david.humphrey@senecacollege.ca 85a8c21dc1 Support file:// URLs and Buffers for path args, throw when invalid 2019-01-02 19:46:36 -05:00
David Humphrey (:humph) david.humphrey@senecacollege.ca 9c13a2d248 Update package-lock.json 2019-01-02 18:08:27 -05:00
David Humphrey 1ad81f9bae Remove WebSQL provider (last supported in v0.0.44) 2019-01-02 13:22:51 -05:00
David Humphrey (:humph) david.humphrey@senecacollege.ca bc861bfd4a Move open files to its own module, properly close fds in tests 2018-12-29 15:11:39 -05:00
David Humphrey (:humph) david.humphrey@senecacollege.ca 11c91acdcf Move device name off fs and onto context 2018-12-29 15:11:39 -05:00
David Humphrey ace4222a82 Update npm deps 2018-12-22 17:24:10 -05:00
David Humphrey 7301024382 Fix #646: add tools/get-filer-version.js to find old Filer versions 2018-12-22 01:02:04 -05:00
David Humphrey 6ec8cd6191 Fix #612: add way to run tests in node, fix docs on running tests 2018-12-21 23:44:59 -05:00
David Humphrey 52baa2523d Release 1.0.2 2018-12-21 23:09:29 -05:00
David Humphrey d4bfcd71c2 Fix #602: fix mode masking issues, correct X_OK case in fs.access 2018-12-21 23:07:33 -05:00
David Humphrey 4f427ed8d7 Update package-lock.json 2018-12-21 22:04:07 -05:00
David Humphrey 22731267a9 Update README for changes in 1.0.x 2018-12-21 15:28:58 -05:00
David Humphrey 9cb4ff7c0a Release 1.0.1 2018-12-21 14:47:00 -05:00
David Humphrey 3dea503289 Include src/ and lib/ in npm package 2018-12-21 14:45:15 -05:00
David Humphrey 909a66efd7 Release 1.0.0 2018-12-21 14:33:38 -05:00
David Humphrey ea236cf43b Fix what we ship in dist/ to match current build 2018-12-21 14:22:25 -05:00
David Humphrey f053c738b8 Fixes to release-it config and npm files 2018-12-21 14:15:45 -05:00
David Humphrey 3afbcca8b3 Fix env.sample format 2018-12-21 13:56:29 -05:00
David Humphrey (:humph) david.humphrey@senecacollege.ca b4c3d1f1ae Remove old config/ dir used by grunt 2018-12-21 13:32:29 -05:00
David Humphrey (:humph) david.humphrey@senecacollege.ca 3f400d17bf Add release-it, config, docs, remove gruntfile.js 2018-12-21 13:32:29 -05:00
David Humphrey (:humph) david.humphrey@senecacollege.ca 1f3b9e79bf Add .npmignore to slim down npm package 2018-12-21 13:32:29 -05:00
David Humphrey (:humph) david.humphrey@senecacollege.ca bfe4385a83 Fix #633: fix test failure in coverage run 2018-12-20 19:00:39 -05:00
David Humphrey (:humph) david.humphrey@senecacollege.ca 5cc21c72fb Fix #639: run tests on Linux and Mac 2018-12-20 18:17:34 -05:00
Julia Yatsenko 9f7f93776e fix #635: added test for fs.ftruncate() 2018-12-20 15:07:17 -05:00
David Humphrey (:humph) david.humphrey@senecacollege.ca 69758613db Stop npm from spamming on test failures 2018-12-18 11:24:41 -05:00
David Humphrey (:humph) david.humphrey@senecacollege.ca 1ae7a220b4 Run migration tests by default after browser tests 2018-12-18 11:04:13 -05:00
David Humphrey (:humph) david.humphrey@senecacollege.ca b5fe85caaa Fixes to pass 0.43 migration test 2018-12-18 11:04:13 -05:00
David Humphrey d0178539f5 Refactor Node to support layout changes with backwad compatibility 2018-12-18 11:04:13 -05:00
David Humphrey (:humph) david.humphrey@senecacollege.ca f738cbc17d Fix #605: add migration tests for Filer 0.43 2018-12-17 21:29:53 -05:00
David Humphrey (:humph) david.humphrey@senecacollege.ca b7312bfa1e Fix how mode gets processed when building images (only use permission bits). 2018-12-17 20:03:23 -05:00
Vince b0809272a1 Included unwatchFile in test index.js
Co-authored-by: David Humphrey <david.humphrey@senecacollege.ca>
2018-12-17 16:39:44 -05:00
Vince fb76c0ec1e Fix #445 test cases for fs.unwatchFile 2018-12-17 16:39:44 -05:00
qwang135 9a7d3514d8 Fix #514: add test for fsPromises.lstat with directory
Co-authored-by: David Humphrey <david.humphrey@senecacollege.ca>
2018-12-17 16:30:21 -05:00
Yuecheng Wu 848cc7d3de Adding more tests for fs.copyFile
Co-authored-by: David Humphrey <david.humphrey@senecacollege.ca>
2018-12-17 16:18:06 -05:00
David Humphrey ba188169d6 Review fixes, skip copyFile test for now 2018-12-17 16:06:24 -05:00
mordax 62cbe11a93 Fixed lint issues in copyFile test 2018-12-17 15:56:55 -05:00
mordax ef80713c33 Added tests for future fs.copyFile implementation and adjusted index.js to run it. 2018-12-17 15:56:55 -05:00
Alexei Kozachenko 0eb7066a86 Added mkdtemp method (issue #441)
Added/fixed mkdtemp method (issue 441)

Added/fixed mkdtemp method (issue 441)

Added/fixed mkdtemp method (issue 441)

fixed a typo

Added mkdtemp method description to readme

Unit tests for mkdtemp method added (issue #394)

Added generateRandom(), randomChars() to shared.js. Corrections in README. Fixes for mkdtemp method

cleaned up mkdtemp()

fixed regex

Fix for failing test (humphd)
2018-12-15 00:39:09 -05:00
David Humphrey 158f6241b6 Fixes from #504 to pass lint, travis 2018-12-15 00:17:43 -05:00
Dan Lin 4a5d8c1222 Fix #456 - add test for fs.write() with undefined path 2018-12-15 00:14:13 -05:00
kwkofler 443b582038 Issue #86: Added support for Unix Timestamps
Co-authored-by: David Humphrey <david.humphrey@senecacollege.ca>
2018-12-14 23:58:42 -05:00
David Humphrey 83bd64fd58 Fix lint issues in #521 2018-12-14 22:18:25 -05:00
imedqq 783e7a9e67 Added newline at end of file 2018-12-14 22:18:25 -05:00
imedqq 2aa6cf2b5f Added promise-based test cases for rmdir 2018-12-14 22:18:25 -05:00
David Humphrey acef2c93b0 Update https://github.com/filerjs/filer/pull/485 to master, add tests + fix. 2018-12-14 22:05:51 -05:00
Deepanjali Gerangal 94fd5ba829 Fix#418-updated method 2018-12-14 19:24:55 -05:00
Deepanjali Gerangal e3a285ae54 fix #418 test for fsPromises.truncate(path[, len]) to test when length is negative 2018-12-14 19:24:19 -05:00
Petr Bouianov 1775c24d37 Fixes issue 75
As the array flags were already reflected in the README documentation
and example, this only required a test
2018-12-14 17:31:31 -05:00
chen yuzhou 3d7ff3e08d Store and reuse the file path 2018-12-12 22:24:11 -05:00
chen yuzhou 1e1c704f7e fix the callers in src/node.js to the correct versio 2018-12-12 22:24:11 -05:00
chen yuzhou e1124993ba Remove duplicate stat.h constants defined in constants.js 2018-12-12 22:24:11 -05:00
David Humphrey 97d2d1bfe3 Fix bug uncovered by new invalid flags test: missing return 2018-12-12 22:09:41 -05:00
David Humphrey 2841b2eba7 Fixes from review 2018-12-12 22:09:41 -05:00
Mera-Gangapersaud 0352dad66c Corrected Travis CI error for issue 500 2018-12-12 22:09:41 -05:00
David Humphrey 307fc3e32c Fix security issue with parcel, update to 1.10.3 2018-12-12 21:53:00 -05:00
David Humphrey 33339b81d7 Fix review issues 2018-12-12 21:38:16 -05:00
Adam 7e941bb304 Update fs.symlink.spec.js 2018-12-12 21:38:16 -05:00
Adam db237e617b update fs.symlink.spec.js based on code review
white spaces , comments added, Promises.Open used
2018-12-12 21:38:16 -05:00
Adam bb9dd2e67c Update README.md 2018-12-12 21:38:16 -05:00
Pooch11 0a1aa0fecc Added tests for symlink using promises api 2018-12-12 21:38:16 -05:00
Pooch11 d894a4cf16 readme dummy changes 2018-12-12 21:38:16 -05:00
David Humphrey 16e6b3e1c9 Fix review issues 2018-12-12 21:31:27 -05:00
Dragomegak af3815c54b Removes Symbolic Link check & Fixing Mixing Callbacks and Promises (Basically the fs.link test though) 2018-12-12 21:27:13 -05:00
Dragomegak 0748951ca8 Changed code to reflect promise syntax 2018-12-12 21:27:13 -05:00
Dragomegak 265f0b1d0d Added fsPromises.link() tests 2018-12-12 21:27:13 -05:00
David Humphrey 1c450ae8e7 Fix review nits, move contents to earlier scope and reuse. 2018-12-12 21:08:30 -05:00
PopeSpaceous 0395c4beae Fix issue-447: Added test to append numbers in fs.appendFile function 2018-12-12 21:08:30 -05:00
jagmeetb 1abcb0369b Fix #431: add test for fsPromises.unlink
add newline at end

implemented suggestions

formatting fixes
2018-12-12 20:59:41 -05:00
David Humphrey d1dd5fef61 Finishing work in #401 2018-12-10 23:57:10 -05:00
Josh Mayers e85880dc8b Fix Issue #399 - added test cases for appendFile with promises 2018-12-10 23:57:10 -05:00
David Humphrey 97a6004091
Fix #604: cli for buidling JSON image from folder (#613)
* Fix #604: cli for buidling JSON image from folder

* Allow passing --filer to specify a filer module to use (different version)

* Deal with fs.chown not existing on older versions of Filer

* Tidy up some loose ends

* Make fs-image.js executable
2018-12-06 22:22:18 -05:00
chen yuzhou 0e75661b4b Remove fs.exists() console spam 2018-12-05 16:23:11 -05:00
David Humphrey 5218057d80 Follow-up from #603, rename ImportExportProvider to SerializableMemoryProvider 2018-12-05 10:18:31 -05:00
David Humphrey 61a1f5e020 Fix #603: add import/export provider to work with JSON fs images 2018-12-04 22:54:29 -05:00
Deepanjali Gerangal 0f93a04e40 Fix for issue #561 - Extend fs.access to support R_OK, W_OK, and X_OK (#601)
* added extended test for fs.access

* making requested changes
2018-12-03 23:08:40 -05:00
David Humphrey (:humph) david.humphrey@senecacollege.ca 0f94c476e7 Fix #597: use built-in path-browserify via Parcel vs. our own path.js 2018-12-03 16:39:04 -05:00
David Humphrey (:humph) david.humphrey@senecacollege.ca 0ed97864ec Add karma summary reporter 2018-12-02 10:25:25 -05:00
David Humphrey (:humph) david.humphrey@senecacollege.ca f5678ebe20 Rebase and rework test, skip() for now, see #594 2018-12-02 10:19:43 -05:00
kwkofler 97fb82769a Issue #158 - Added test to ensure that watchers monitoring hardlinks are notified when the original file is updated 2018-12-02 10:19:43 -05:00
David Humphrey (:humph) david.humphrey@senecacollege.ca 7d196763f8 Update docs, fix test failure 2018-12-02 00:05:57 -05:00
kwkofler 6a5d9073f3 Issue 87 - Added fs.fsync() as a no-op, and added tests. Modified documentation.
Made requested changes to tests, functionality; reverted doc changes
2018-12-02 00:05:57 -05:00
David Humphrey (:humph) david.humphrey@senecacollege.ca a107fe21d7 Fix #337: Pick up sedge's changes from 3c49743559 2018-12-01 22:20:09 -05:00
David Humphrey (:humph) david.humphrey@senecacollege.ca d7945d745d Fix #577: deal with promise exceptions and test console spam 2018-12-01 22:07:24 -05:00
David Humphrey (:humph) david.humphrey@senecacollege.ca 923b999e89 Fix #547: update Buffer use, docs, tests to match node.js v11.3.0 2018-12-01 20:05:05 -05:00
David Humphrey 9acedc2beb (no bug) Update CONTRIBUTING.md to reflect test changes 2018-12-01 12:50:04 -05:00
David Humphrey 395406609d Add Headless Firefox test support, fix failing truncate test in Firefox 2018-12-01 12:38:39 -05:00
David Humphrey (:humph) david.humphrey@senecacollege.ca cc6e3f7edf Increase coverage: check for non-int with chown/fchown 2018-11-29 22:47:26 -05:00
David Humphrey 43d2632069 Improve coverage: add test for rel paths with symlink 2018-11-29 16:57:06 -05:00
David Humphrey 7ab229a64c Fix #572: remove lib/nodash.js, use builtins instead 2018-11-28 22:54:31 -05:00
yatsenko-julia f57c7330d3 fix #556: added tests for fs.ftruncate method (#557)
* fix #556: added tests for fs.ftruncate method

* Update fs.ftruncate.spec.js
2018-11-28 22:42:17 -05:00
David Humphrey 89cfef0f07 Remove dead code in src/shared.js u8toArray() 2018-11-28 22:23:51 -05:00
David Humphrey d1cf1286cb Fix #576: remove unnecessary methods from fs.promises, adjust tests to match 2018-11-28 19:42:32 -05:00
David Humphrey 2135ee17e9 Update fs.stat.spec.js to not have uncaught exception on promise 2018-11-28 19:41:46 -05:00
David Humphrey 725bfbf30c
Fixes #422: Add nyc lcov-based code coverage for tests (#565)
* Add nyc lcov-based code coverage for tests

* Add codecov to travis

* Add codecov badge to README
2018-11-28 19:24:03 -05:00
yuzhouChen 89626107cc Fix #568: switch all stats.type checks in tests/ to use is*() methods (#581)
* Fix Issue#568

* Fix issue 568: two more file changes

* Fix issue 568: more changes in tests/spec/shell/ls.spec.js
2018-11-28 13:54:20 -05:00
Susan Truong a25d71b524 Fix #435: add a test for fsPromise.unlink() to delete a file that does not exist
Make changes to `fsPromises.unlink()` to be more promise-friendly

Added a newline to the end of the file

Made a change to fsPromises.unlink() to be more friendly

Changed the description of the promises test
2018-11-27 13:18:39 -05:00
Alan K d1afe9719d
Merge pull request #476 from steaward/issue-420
Fixes #420
2018-11-22 01:46:52 -05:00
Deepanjali Gerangal 400b2c3c88 Fix #558 - Implementing fs.access() method (#560)
* Implementing fs.access() method

* added new line to access.js

* updated requested changes

* updated README.md with fs.access

* fixing truncate error

* updated README.md

* changed access.js to access.spec.js
2018-11-17 15:31:20 -05:00
David Humphrey ea95badc5b Update dist/ built versions of Filer 2018-10-30 14:35:33 -04:00
Rikku-x a5fc0e699a #541 Grammatical error (#554) 2018-10-20 17:00:03 -04:00
Alexander Ponomaroff ce030b91fa Fix issue #398 - Add testing for promises to all test cases in fs.writeFile-readFile.spec.js file (#402)
* Fix issue #398 - Add testing for promises to all test cases in fs.writeFile-readFile.spec.js file

* Fix issue #398 - Add testing for promises to all test cases in fs.writeFile-readFile.spec.js file

* Fixed requested issues

* Further Improvement
2018-10-20 16:59:26 -04:00
Deepanjali Gerangal 5568c27bec fix for #542 for fsPromises.symlink(target, path[, type]) (#543)
* updating fs.symlink for promises

* updated the requested changes

* fix#542 added a newline at end
2018-10-20 16:57:45 -04:00
Volodymyr Klymenko bfcb5a6a94 Added tests for Promises version of mkdir (#415) 2018-10-16 19:27:12 -04:00
ThomasNolte 3bbabfcb4a added tests for fs.promises.chown() closes #465 (#471)
* added tests for fs.promises.chown() for check if function exists and updating gid/uid for a file

* update to pass lint tests

* cleaned up code. replaced all callbacks with promises in new test.

* Revert "lint tests fix"

This reverts commit 3c256124cf, reversing
changes made to 71a6f514fc.

* Revert "cleaned up code. replaced all callbacks with promises in new test."

This reverts commit 71a6f514fc.

* Made requested changes.
2018-10-16 11:43:59 -04:00
Shawn Pang 1eab5f0ffd Fix#461 - Added test for fs.read when attempting to read a file that does not exist (#472)
* Added test for fs.read when attempting to read a file that does not exist

* Added test for fs.read when attempting to read a file that does not exist

* Modified read test for non-existent file to act more similar to earlier tests

* Added check in read test for error code
2018-10-16 11:22:54 -04:00
yatsenko-julia 73f0f19bb9 Fix #523: added tests for fs.ftruncate() (#524)
* Fix #523: added tests for fs.ftruncate()

* fix #523: moved a function from truncate to ftruncate and made a few minor changes

* Fixed indentation
2018-10-16 11:21:49 -04:00
bblarney 707d404db0 Issue 417 - Added test for fs.promises.rename to rename existing directory (#460)
* test added

* working so far

* done

* cleaned up a catch

* made some requested changes
2018-10-16 11:07:10 -04:00
VictorKubrak a447b2dd45 rename() should be able to rename an existing file to the same filename (#502)
* rename should not change name to itself

* new test expects failure

* should rename an existing file to itself

* should rename an existing file to itself

* Update tests/spec/fs.rename.spec.js

* add .skip to the test
2018-10-16 09:43:44 -04:00
AHKol 8aa8dda4d6 Fix #411: Tests if event is thrown when calling rename (#478)
* Fix #411: Tests if event is thrown when calling rename

* npm run lint:fix

* Added comment explaining lack of 'rename' event check
2018-10-15 16:33:47 -04:00
Stephen Ward 08b0b3001e removed pre-existing comment about open() 2018-10-10 22:48:13 -04:00
Stephen Ward 675773b92a re-added the newline, as well as another test case to make sure mode is still set to default value when a new file is opened 2018-10-10 15:10:34 -04:00
Janice 41510e7da4 Fix issue 529 (#530)
* Fix issue 529

* Fix Issue 529

* Fix issue 529 and some indentations

* fix arrow function instead of function expression

* Fix issue529

* Fix issue529

* Saving files before refreshing line endings

* done

* push again

* change sth

* changed
2018-10-09 21:17:25 -04:00
jrkong b1c4f04f83 Removed outdated about permission functions in README.md (#513) 2018-10-09 20:53:32 -04:00
Stephen Ward ee67cb39de rolled back the package-lock.json to master's version 2018-10-09 20:34:09 -04:00
Stephen Ward e11c101600 forgot a semicolon 2018-10-09 20:28:46 -04:00
Stephen Ward 7a6a4160e6 made changes as per thomas's and dave's PR review 2018-10-09 20:25:19 -04:00
pynnl c33f22b464 Issue 396 - Add a test for fs.promises.stat() when the path does not exist (#406)
* test non exist path for promise

* fix new line at the end

* fix missing semicolon 113:26

* follow 'Testing promise codes' on guidline
2018-10-09 17:40:35 -04:00
Julia McGeoghan 389dedd3c0 Fix #421 - Add test for fs.promises.link to ensure it returns a Promise (#462)
* Add test

* Move location of describe block

* Remove comment

* Have test check returnValue and not obj

* Override package-lock.json with one from master branch

* Improve naming of fsPromise variable to be more clear
2018-10-09 17:35:28 -04:00
yuzhouChen 8504cc7e2a Issue497 Add test for fs.chmod when the path is invalid (#525)
* Fix #497 Add test for fs.chmod when the path is invalid

* Fix #497 All test passed
2018-10-09 17:30:36 -04:00
yevseytsev 27659d45da 491 (#501)
* mkdir - restricted symbols('?' only)

* FINAL
2018-10-09 17:28:14 -04:00
Stephen Truong 934ef8bfa7 Fix #419: Add test for fsPromises.open() when the path does not exist (#455)
* Fix #419: Add test for fsPromises.open() when the path does not exist

* Update package.json

* Fix #419: Add test for fsPromises.open() when the path does not exist

Removed some unnecessary code based on reviews

* Update fs.open.spec.js
2018-10-09 16:00:56 -04:00
Ruihui Yan c7ea45a18b Fix issue #475 - Add test for fs.exits() when resulting path of a symbolic link is not found (#519)
* add test for exits when resulting path of a symbolic link is not found

* fixed style nit
2018-10-09 14:31:15 -04:00
Sean 009821290f Fixes #499: Update functionality for fs.truncate (#533)
* Fixes #499: Update functionality for fs.truncate

This change to fs.truncate()'s functionality throws an error when the
length to truncate by is a non-numeric string.

* Refactor numeric type validation

As node implements a helper function to validate numeric values, let's
replicate the same logic to use throughout Filer.
2018-10-09 13:53:26 -04:00
Thanh Nguyen 2f3c384868 Add test for fsPromises.rmdir() when dir not empty and dir is a file, Fix Issue 474 (#510)
* Saving files before refreshing line endings

* Adding test case for returning an error if the path is not a directory

* Add return for fsPromises, and few other small fixes

* Fix promises, and few done parameter

* Update fs.rmdir.spec.js
2018-10-09 13:51:19 -04:00
giantpanpan beea03dbae Add test for fs.writeFile-readFile.spec to write a file in non-existing path (#486) 2018-10-09 13:48:51 -04:00
ywpark1 3e0da99040 Fix issue-426: Add the test for fsPromises.readdir when the path exists, and is a directory (#452) 2018-10-09 13:32:09 -04:00
dleung25 02bd6d8a62 Issue#518 fix: Add test for fsPromises.unlink() should be a function (#526)
* issue518 fix

* changed back to original package.json

* add newline to end of file
2018-10-09 13:27:22 -04:00
Jeffrey Espiritu 7e27c8be2c Fix Issue #400 - add test for passing file to fs.promise.readdir() (#409)
* Fix Issue #400 - add test for passing file to fs.promise.readdir()

This adds a test to ensure that `fs.promise.readdir()` throws an error when passing in a file.

* Made changes to `fsPromises.readdir` to be more promise-friendly
2018-10-09 13:04:19 -04:00
Casva e77361107e Issue 427 - Add tests to fsPromises.rmdir when directory doesn't exist and when trying to delete root directory (#457)
* Fix #427 - Fixed indentation and ENOENT -> EBUSY on line 120

* Deleted extra line at the end of document

* Fix #427 - Added tests for fsPromises.rmdir when trying to remove a nonexistent directory and when trying to remove root directory
2018-10-09 13:02:01 -04:00
Daniel Bogomazov 87230ce1e3 Fix #405 - Added tests for chmod and fchmod using Promises (#458)
* Added tests for chmod and fchmod using Promises

* Remove unrelated files from pull request

* Fixed spelling mistake

* Removed redundant catch blocks
2018-10-09 12:59:17 -04:00
Huda Al Dallal 2e2e2f9d64 Fixed issue#480 using promises to test fs.truncate when path does not exist (#516)
* added a test for issue#480 using promises to test fs.truncate

* Fixed issue#480 tesing fs.truncate using promises when path does not exist
2018-10-09 12:56:20 -04:00
rdittrich97 0354c7e13e Fix #423: added proimse support for fs.stat (#432)
* added promise support to fs.stat

* restored package lock

* fixed lint issues

* made tests more promise freindly

* removed .catch statement from promise and fixed style issues

* removed .catch statement from promise and fixed style issues
2018-10-09 12:54:40 -04:00
y2s82 1156f420c4 Fixed #424 - implement fs.promises.read tests (#429)
* implemented first two tests of fs.promises.read

* simplified the 2nd fs.promises.read test

* implemented test on file position update for fs.promises.read

* implemented directory read failure test for fs.promises.read

* implemented test to check the return type to be a Promise in fs.promises.read

* fixed indentation and also fixed a catch statement to allow all code to be reachable

* made tests more promise-friendly

* applied some style changes and test changes as per @rdittrich97 suggestions

* removed lines that are unnecessary for promise-based testing and syntactically simplified some function definitions

* removed more unnecessary check lines in directory check fail test
2018-10-09 12:51:59 -04:00
Nick Skuybeda 86b6b2a907 Fixed Issue #483 for a test done for fs.mknod promise (#509)
* test done for fs.mknod promise

* fixing whitespaces
2018-10-09 12:43:45 -04:00
Chaya Danzinger a8759b1e38 Add tests for fs.promises utimes function #527 (#540)
* first two promise tests initial commit

* implemented existing tests but with promises

* add final tests

* add return statement for remaining tests

* fix function call error
2018-10-09 12:39:18 -04:00
David Humphrey c84dd14f5e
Merge pull request #395 from humphd/issue-393
Fix #393: add test for truncate with length undefined
2018-10-03 18:13:08 -04:00
rhayes2 31b3c40d74 Line ending fix 2018-09-25 00:35:46 -04:00
rhayes2 7a716e033b Add chmod --test for chmode mode value 2018-09-25 00:31:49 -04:00
rhayes2 395de63751 aDD Chmod --test for chmod 2018-09-25 00:29:33 -04:00
rhayes2 7f155a0f40 Add chmod test with incorrect mode value 2018-09-25 00:27:31 -04:00
rhayes2 294685d6cb Style fix 2018-09-25 00:15:07 -04:00
Stephen Ward 62b85d1442 i did it again...forgot to remove an unused variable so travis-ci test failed. 2018-09-24 23:32:11 -04:00
Stephen Ward 30752c9109 added a test: open a new file for writing, and set a mode for that file 2018-09-24 23:28:56 -04:00
Stephen Ward f3a7170133 removed an unused variable, because I was using it for those console.logs which I just deleted 2018-09-24 19:17:19 -04:00
Stephen Ward 833ac62c45 removed some console.logs because travis-ci complained 2018-09-24 19:14:08 -04:00
Stephen Ward 78b3452d5d added the addition of an optional mode when opening a file, removed my test because it was broken. Seemingly passes all the other tests still. STILL TO DO: add a proper test which makes sure the mode is set. 2018-09-24 19:10:09 -04:00
Stephen Ward e7811eb53b fixed lint spaces/indentation errors 2018-09-24 17:46:01 -04:00
rhayes2 546b4567d2 Added Test for CHMODE 2018-09-24 14:16:16 -04:00
Corey James e3a1187ef9 Fixed the fs.read() example in doc. The error checking statements were using the wrong variable name (#449) 2018-09-24 14:08:49 -04:00
rhayes2 499c72daaf saving for lineending dumbness 2018-09-23 21:19:57 -04:00
Stephen Ward add00ce563 testing out the validateAndMask() function, with console.log's... 2018-09-23 13:49:00 -04:00
David Humphrey (:humph) david.humphrey@senecacollege.ca 5e4de6b698 Fix #393: add test for truncate with length undefined 2018-09-17 18:30:09 -04:00
0xazure fd3de6be2c Update karma dev dependency
Resolves `npm audit` warnings about 1 low, 5
moderate vulnerabilities related to versions before
karma@3.0.0.

Closes #384.
2018-09-12 21:43:58 -04:00
Dmytro 353290a08f Adding support for promises. Closes #379, #382 (#380)
* adding promise-based filedescriptor

* fixing promisify dep

* promisifying shell

* deprecating 'exists' method on fs

* adding docs

* fixing docs

* removing redundant code.
2018-08-27 19:50:41 -04:00
Alan K de45918cbc
Merge pull request #378 from humphd/karma
Automate tests using Headless Chrome + Karma runner
2018-08-21 14:54:48 -04:00
David Humphrey 53f5b0c50b Fix script names in package.json 2018-07-27 11:23:27 -04:00
David Humphrey 7798b1cb87 Fix lint issues in implementation.js 2018-07-27 11:23:06 -04:00
David Humphrey 0da0e60194 Fix lint issues in interface.js 2018-07-27 11:17:45 -04:00
David Humphrey dc8fa4cb96 Fix lint issues in node.js 2018-07-27 11:17:03 -04:00
David Humphrey 3a44c1756a Fix lint issues in src/path.js 2018-07-27 11:16:30 -04:00
David Humphrey 8d553b78e0 Fix lint issues in indexeddb.js provider 2018-07-27 11:14:08 -04:00
David Humphrey b92151cdc5 Fix lint issues in websql.js provider 2018-07-27 11:13:40 -04:00
David Humphrey bcf4d9834a Don't build source map for karma test bundle 2018-07-27 11:12:25 -04:00
David Humphrey ed11b01234 Fix lint issues in shell.js 2018-07-27 11:12:06 -04:00
David Humphrey 0980ec4608 Fix lint issues in issue258.js 2018-07-27 11:09:45 -04:00
David Humphrey a31044cc8d Fix lint issues in issue267.js 2018-07-27 11:08:40 -04:00
David Humphrey 454d5bc801 Fix lint issues in ls-depth-bug.js 2018-07-27 11:07:17 -04:00
David Humphrey d41885e9d0 Fix lint issue in tests/lib/indexeddb.js 2018-07-27 11:03:43 -04:00
David Humphrey 0e00af661a Fix lint issues in fs.appendFile.spec.js 2018-07-27 11:02:42 -04:00
David Humphrey f89b616fdc Fix issues in fs.chmod.spec.js 2018-07-27 11:01:47 -04:00
David Humphrey cbcddee3be Fix lint issues in fs.chown.spec.js 2018-07-27 11:01:26 -04:00
David Humphrey 1a738dd2bb Fix lint issues in fs.close.spec.js, fs.link.spec.js 2018-07-27 11:00:48 -04:00
David Humphrey 9e08d96c96 Fix lint issues in fs.lstat.spec.js 2018-07-27 10:44:42 -04:00
David Humphrey 980d5d0917 Fix lint issues in fs.lseek.spec.js 2018-07-27 10:43:51 -04:00
David Humphrey a8e373e4b9 Fix lint issues in fs.mknod.spec.js 2018-07-27 10:39:34 -04:00
David Humphrey 86e57d60db Fix lint issues in fs.open.spec.js 2018-07-27 10:38:44 -04:00
David Humphrey 054094c852 Fix lint issues in fs.read.spec.js, fix test failure in fs.stats.spec.js 2018-07-27 10:37:45 -04:00
David Humphrey cafff52c3a Fix lint issues in fs.rename.spec.js 2018-07-27 10:34:21 -04:00
David Humphrey 1c7b40c895 Fix lint issues in fs.stats.spec.js 2018-07-26 18:17:05 -04:00
David Humphrey 7258a2913e Fix lint issues in fs.truncate.spec.js 2018-07-26 18:07:50 -04:00
David Humphrey bb8743eda1 Fix lint issues in fs.unlink.spec.js 2018-07-26 18:02:16 -04:00
David Humphrey 94e6a98cb8 Fix lint issues in fs.utimes.spec.js 2018-07-26 18:01:21 -04:00
David Humphrey ee8e2a665a Fix lint issues in fs.writeFile-readFile.spec.js 2018-07-26 18:01:07 -04:00
David Humphrey a93ae13c99 Fix lint issues in fs.xattr.spec.js 2018-07-26 17:56:54 -04:00
David Humphrey ab87c7f14a Fix lint issues in tests-fs-watch.js 2018-07-26 17:54:26 -04:00
David Humphrey 49931722cc Fix lint issues in path-resolution.spec.js 2018-07-26 17:53:02 -04:00
David Humphrey 3e1c3deb51 Fix lint issues in providers.base.js 2018-07-26 17:50:32 -04:00
David Humphrey a8c3fa85db Fix lint issues in exec.spec.js 2018-07-26 17:44:27 -04:00
David Humphrey 51c81edb5b Fix lint issues in touch.spec.js 2018-07-26 17:41:35 -04:00
David Humphrey 8e900a3a88 Fix lint issues in time-flags.spec.js 2018-07-26 17:39:19 -04:00
David Humphrey 4a066064f4 Fix lint issues in times.spec.js 2018-07-26 17:37:26 -04:00
David Humphrey e5b6026b91 Add docs for running eslint/lint scripts 2018-07-15 13:28:04 -04:00
David Humphrey a900d8df6d Add eslint --fix scripts, fix first round of lint errors 2018-07-15 13:25:35 -04:00
David Humphrey 2ad0d0eb8b Automate tests using Headless Chrome + Karma runner 2018-07-15 13:08:56 -04:00
Alan K 04f9c57cd8
Merge pull request #374 from humphd/parceljs
Switch to parceljs for bundling, eslint for linting, drop grunt
2018-07-14 12:49:55 -04:00
David Humphrey e155c2d1a0 Remove unneeded requirejs dep 2018-07-14 11:25:17 -04:00
David Humphrey 9832807dd1 Rebase and update to changes on develop 2018-07-14 11:21:34 -04:00
David Humphrey (:humph) david.humphrey@senecacollege.ca 65bbc17ccb Update package.json + tests/ to support browser property for bundlers, delete old useless tests for AMD 2018-07-14 10:53:23 -04:00
David Humphrey (:humph) david.humphrey@senecacollege.ca c15145cc03 Fix tests so they work and pass with Parcel.js, updated outdated, remove .babelrc 2018-07-14 10:50:43 -04:00
David Humphrey (:humph) david.humphrey@senecacollege.ca d61c61aab8 Switch to parceljs for bundling, eslint for linting, drop grunt 2018-07-14 10:50:22 -04:00
Alan K 2e90fdae0c
Merge pull request #373 from humphd/9p-filer
Update Filer to support Plan 9 virtio filesystem API in v86
2018-07-14 10:21:35 -04:00
David Humphrey 9ded3ea1eb Fixup comment that got removed 2018-07-14 10:02:29 -04:00
David Humphrey 3da99f0133 Update README with new info about additional APIs 2018-07-14 10:02:29 -04:00
David Humphrey 31cd579682 Add updated dist/ built files 2018-07-14 10:02:29 -04:00
David Humphrey b7ecae4af1 Fix typos and clean up for review 2018-07-14 10:02:29 -04:00
David Humphrey 46698f30e2 Add package-lock.json 2018-07-14 10:02:29 -04:00
David Humphrey c71a91f72f Update dist/ with newest stuff 2018-07-14 10:02:29 -04:00
David Humphrey eee8200e23 Remove FirefoxOS hack for https://github.com/humphd/next/issues/59 2018-07-14 10:02:29 -04:00
David Humphrey 1087371fc4 Deal with file type bits in mode when setting permissions via chmod 2018-07-14 10:02:29 -04:00
David Humphrey 4e73ef8d9b Allow relpaths for symlink targets (needed by P9vfs), get rid of path info in Node 2018-07-14 10:02:29 -04:00
David Humphrey 9508833b37 Add chown, fchown, chmod, fchmod and tests. 2018-07-14 10:02:29 -04:00
David Humphrey e77a8bacd3 Add fs.constants and file mode permissions 2018-07-14 10:02:29 -04:00
David Humphrey bf1d0e41d6 Fix bug with stats.name generated from fd, add tests 2018-07-14 10:02:29 -04:00
David Humphrey c526445a43 Fix mode, fs.link, fix other bugs and cleanup 2018-07-14 10:02:29 -04:00
David Humphrey 0aaaeacd1a Update sh.ls and stats to remove bits I don't need, add what I do. 2018-07-14 10:02:29 -04:00
David Humphrey ee412d4abe Restructure layout of node 2018-07-14 10:02:29 -04:00
David Humphrey 9244e9be6e Switch from .mode to .type on nodes 2018-07-14 10:02:29 -04:00
David Humphrey 2efb956411 Switch from MODE_* to NODE_TYPE_* 2018-07-14 10:02:29 -04:00
David Humphrey 93633da622 All basic operations now working in Linux 9P mounted fs 2018-07-14 10:02:29 -04:00
David Humphrey 2e627cfe5b Update Filer for things needed for Plan 9 sharing 2018-07-14 10:02:29 -04:00
Alan K b026537f09
Merge pull request #377 from filerjs/travis-node-update
Changes Node version to 8.11.3
2018-07-13 23:56:47 -04:00
Alan K f771f48e8b Changes Node version to 8.11.3 2018-07-13 23:52:01 -04:00
David Humphrey 2a4674d11f Merge pull request #370 from humphd/fix-indexeddb-transactions
Use transaction per operation in indexeddb.js, fix broken async tests in fs.stats.spec.js
2017-05-25 10:08:54 -04:00
David Humphrey (:humph) david.humphrey@senecacollege.ca 18a470e264 Update dist/ with updated built scripts for code changes 2017-05-25 10:05:32 -04:00
David Humphrey (:humph) david.humphrey@senecacollege.ca 3650b798ed Use transaction per operation in indexeddb.js, fix broken async tests in fs.stats.spec.js
Fixing for review comments

Switch to RW or RO transaction per get/put/delete/clear, better error handling for try/catch cases

Switch back to transaction-per-context for better atomic fs operations.

Move _getObjectStore onto prototype
2017-05-25 10:04:20 -04:00
David Humphrey 6d3cec89ee Merge pull request #369 from bryant1410/develop
Fix broken headings in Markdown files
2017-04-18 10:42:33 -04:00
Santiago Castro 68cbd54524 Fix broken Markdown headings 2017-04-18 02:34:52 -03:00
David Humphrey c8f217fbcd Merge pull request #367 from orthographic-pedant/spell_check/conjunction
Fix typographical error(s)
2015-10-07 14:55:23 -04:00
orthographic-pedant 3ddb877276 Fix typographical error(s)
Changed conjuction to conjunction in README.
2015-10-07 14:47:53 -04:00
Alan K 525e11f203 Suppress console.error message in test case 2015-08-16 13:18:26 -04:00
Alan K ddc41f49a5 Fixed default provider when no query string is passed 2015-08-16 13:14:31 -04:00
Alan K 9f625c0d0f Merge branch 'develop' of github.com:filerjs/filer into develop 2015-08-16 13:03:10 -04:00
Alan K 8325b5a9d7 Add a new 'default' provider option so we can force the memory provider
for testing
2015-08-16 13:02:39 -04:00
Alan K d66114e20c v0.0.44 2015-07-21 14:40:33 -04:00
Kieran Sedgwick 9101db2344 Fixed #360 - Added newly exposed internal modules to release commits 2015-07-21 11:47:17 -04:00
Alan K 4de8bc4b81 v0.0.43 2015-07-16 17:56:12 -04:00
Alan K 047536c013 v0.0.42 2015-07-16 17:51:55 -04:00
David Humphrey 6549a98b6a Merge pull request #359 from humphd/issue357
Fix #357 - Path.resolve() should not crash with missing Path.relative()
2015-06-29 13:05:27 -04:00
David Humphrey (:humph) david.humphrey@senecacollege.ca 03896eef05 Update package.json for node 12.5, browserify, uglify, and build dist/ 2015-06-29 12:29:46 -04:00
David Humphrey (:humph) david.humphrey@senecacollege.ca c85fa1851f Fix #357 - Path.resolve() should not crash with missing Path.relative() 2015-06-29 11:38:51 -04:00
Kieran Sedgwick f338991ace Fixed #352 - Removed `process` from browserified version of filer 2015-06-01 16:42:05 -04:00
Kieran Sedgwick 1df35e1834 Fixed #354 - Add standalone Path and filer-buffer modules 2015-06-01 15:08:23 -04:00
David Humphrey (:humph) david.humphrey@senecacollege.ca a13297449d New built versions of filer for fs.rename() fix 2015-05-12 15:44:26 -04:00
David Humphrey f143ea0ce7 Merge pull request #351 from humphd/rename-dir-trailing-slash
fs.rename() should normalize paths before using, dir vs. dir/
2015-05-12 15:27:05 -04:00
David Humphrey (:humph) david.humphrey@senecacollege.ca 17fb8993c3 fs.rename() should normalize paths before using, dir vs. dir/ 2015-05-12 15:16:32 -04:00
Gideon Thomas e9c4cb6d7a Fix #340 - Set provider type for unit tests in the browser 2015-03-30 10:30:50 -04:00
Alan K 78f9ce824d Merge pull request #347 from sedge/issue313-buildDocs
Fix #313: Update docs to include build tasks
2015-02-05 18:22:37 -05:00
Kieran Sedgwick 4dc2bce59d Update gruntfile to match documentation 2015-01-20 14:59:36 -05:00
Kieran Sedgwick 0f63c0988c First revision complete 2015-01-20 14:56:10 -05:00
Kieran Sedgwick af0698a859 Initial commit 2015-01-16 19:09:45 -05:00
Alan K db4274f1d2 Merge pull request #344 from sedge/issue321-updateVersionNo
Fixed #321 - Make grunt-git point upstream
2015-01-13 11:51:07 -05:00
Kieran Sedgwick 4b01317189 Fixed #321 - Make grunt-git point upstream 2015-01-13 09:54:03 -05:00
Alan K 28e981c0c1 Merge pull request #341 from gideonthomas/issue339
Fix #339 - fs.rename tests fail on the browser
2014-12-17 17:13:09 -05:00
Gideon Thomas 67dba10d49 Fix #339 - fs.rename tests fail on the browser 2014-12-17 15:08:13 -05:00
Alan K 841360de71 Merge pull request #335 from gideonthomas/issue334
Fix #334 - Do not allow fs.link on directories
2014-12-17 14:22:40 -05:00
Gideon Thomas 8c4de99a98 Fix #334 - Do not allow fs.link on directories 2014-12-17 13:30:31 -05:00
Alan K 2347e12db2 v0.0.41 2014-12-17 02:52:53 -05:00
Alan K fbb55c86e6 gitrm can't handle directories :/ 2014-12-17 02:52:20 -05:00
Alan K db23ae2bd2 v0.0.40 2014-12-17 02:48:27 -05:00
Alan K ef9df89517 force rm on tests/ and perf/ for gh-pages 2014-12-17 02:47:48 -05:00
Alan K 4e31547270 v0.0.39 2014-12-17 02:46:41 -05:00
Alan K 830c6adde6 v0.0.38 2014-12-17 02:43:18 -05:00
Alan K 8c0f8eaac8 add tests/ and perf/ to gh-pages update 2014-12-17 02:42:40 -05:00
Alan K 2b6d54cbf4 v0.0.37 2014-12-17 02:35:01 -05:00
Alan K 5798beb99f Merge pull request #338 from filerjs/perf
fix up perf tests
2014-12-17 02:34:18 -05:00
Alan K 9e3f48d783 fix up perf tests 2014-12-16 18:53:29 -05:00
Alan K f812ad406d Merge pull request #333 from yoavgurevich/issue303
Issue #303: Performance Test Fix-up
2014-12-16 01:09:04 -05:00
Alan K 68070d0768 Merge pull request #309 from gideonthomas/issue308
Fix #308 - fs.rename does not work on directories
2014-12-08 14:04:21 -05:00
gideonthomas d28100c422 Fix #308 - fs.rename does not work on directories 2014-12-06 16:34:36 -05:00
yoavgurevich 32265e92d7 PR corrections 2014-12-04 09:23:38 -05:00
yoavgurevich d720f65d23 logic thus far 2014-12-03 18:33:07 -05:00
yoavgurevich b4efa7d2a4 Initial work 2014-12-03 17:25:30 -05:00
Alan K e39129a7f4 Merge pull request #326 from gideonthomas/issue297
Fix #297 - Provide better initialization errors
2014-12-03 00:30:39 -05:00
Alan K f160f540a0 v0.0.36 2014-12-02 13:45:21 -05:00
Alan K d6c77abfa0 Merge pull request #331 from humphd/issue329
Fix #329 - Implement Shell.find()
2014-12-02 11:23:43 -05:00
David Humphrey (:humph) david.humphrey@senecacollege.ca 21b602ef66 Fix #329 - Implement Shell.find() 2014-11-28 15:05:47 -05:00
Alan K 76d256f744 Merge pull request #330 from humphd/cleanup-callback
Ensure test providers deal with missing callback early
2014-11-27 11:20:50 -05:00
David Humphrey (:humph) david.humphrey@senecacollege.ca 4cdcca1a8d Ensure test providers deal with missing callback early 2014-11-27 10:31:49 -05:00
Gideon Thomas 286074f519 Fix #297 - Provide better initialization errors 2014-11-22 12:47:42 -05:00
Alan K b1cf2d7dfb Merge pull request #325 from gideonthomas/issue256
Fix #256 - fs.read() for dir paths should fail
2014-11-20 12:32:33 -05:00
Gideon Thomas 91f7bf0319 Fix #256 - fs.read() for dir paths should fail 2014-11-16 00:12:53 -05:00
Alan K 1283535d75 Merge pull request #322 from sedge/issue208-dontTorchGhPages
Fix #208 - Prevent grunt publish from destroying the gh-pages branch
2014-11-14 16:07:58 -05:00
Kieran Sedgwick 63f5fdeb6c Fix #208 - Prevent grunt publish from destroying the gh-pages branch 2014-11-14 12:18:36 -05:00
Kieran Sedgwick 0d4110ff6f Fixed #323 - Updated references to "fs.Shell" in the docs and test suite 2014-11-14 12:04:51 -05:00
Alan K f8ca6e8208 Merge pull request #315 from sedge/issue312-bundleTests
Fix #312 - Bundle filer-test.js with gh-pages branch only
2014-11-11 16:39:35 -05:00
Alan K 9612cbcbdc Merge pull request #310 from sedge/issue245-ShellConstructor
Fix #245 - Forced the user to manually instantiate FileSystemShell objec...
2014-11-11 16:36:06 -05:00
Kieran Sedgwick 483d3fef72 Fix #312 - Bundle filer-test.js with gh-pages branch only 2014-11-06 11:24:02 -05:00
Kieran Sedgwick a05faf0b2a Review fixes 2014-11-06 10:31:45 -05:00
Kieran Sedgwick 3178ad9a45 Review fixes 2014-11-04 13:03:49 -05:00
Kieran Sedgwick c4c13c1535 Fix #245 - Forced the user to manually instantiate FileSystemShell objects 2014-11-04 13:03:49 -05:00
166 changed files with 41034 additions and 41236 deletions

1
.eslintignore Normal file
View File

@ -0,0 +1 @@
tests/dist/

36
.eslintrc.json Normal file
View File

@ -0,0 +1,36 @@
{
"env": {
"browser": true,
"commonjs": true,
"es6": true,
"mocha": true,
"node": true
},
"extends": "eslint:recommended",
"parserOptions": {
"ecmaVersion": 2017,
"sourceType": "module"
},
"rules": {
"indent": [
"error",
2
],
"linebreak-style": [
"error",
"unix"
],
"quotes": [
"error",
"single"
],
"semi": [
"error",
"always"
],
"eqeqeq": [
"error",
"always"
]
}
}

1
.gitattributes vendored Normal file
View File

@ -0,0 +1 @@
* text=auto eol=lf

27
.github/workflows/node-js-ci.yml vendored Normal file
View File

@ -0,0 +1,27 @@
name: node-js-ci
on:
pull_request:
branches:
- master
push:
branches:
- master
jobs:
build:
runs-on: ${{matrix.os}}
strategy:
matrix:
os: [ubuntu-latest, macos-latest, windows-latest]
node: ['14', '16']
name: Node ${{ matrix.node }} on ${{ matrix.os }}
steps:
- uses: actions/checkout@v2
- name: Test
uses: actions/setup-node@v2.4.1
with:
node-version: ${{ matrix.node }}
- run: npm install
- run: npm test

12
.gitignore vendored
View File

@ -1,5 +1,13 @@
node_modules
bower_components
.env
*~
dist/filer-issue225.js
.vscode
.idea
# Parcel build dirs
.cache
tests/dist
# nyc code coverage
.nyc_output
coverage

1
.npmrc Normal file
View File

@ -0,0 +1 @@
loglevel=silent

17
.release-it.json Normal file
View File

@ -0,0 +1,17 @@
{
"hooks": {
"before:init": ["npm run test"],
"before:bump": ["npm run build"]
},
"git": {
"pushRepo": "git@github.com:filerjs/filer.git",
"tagName": "v${version}"
},
"npm": {
"publish": true
},
"github": {
"pushRepo": "git@github.com:filerjs/filer.git",
"release": true
}
}

View File

@ -1,9 +1,32 @@
sudo: false
language: node_js
node_js:
- "0.10"
before_install: npm install -g grunt-cli
- "lts/*"
cache:
directories:
- "node_modules"
os:
- linux
- osx
# Setup headless Firefox and Chrome support
# https://docs.travis-ci.com/user/gui-and-headless-browsers/#Using-the-Chrome-addon-in-the-headless-mode
env:
- MOZ_HEADLESS=1
addons:
chrome: stable
firefox: latest
before_install:
- google-chrome-stable --headless --disable-gpu --remote-debugging-port=9222 http://localhost &
after_success:
- npm install -g codecov
- npm run coverage
- codecov
notifications:
email: false
irc: "irc.mozilla.org#filer"
env:
- "FILER_UPSTREAM_URI=\"default\" FILER_UPSTREAM_BRANCH=\"default\" FILER_UPSTREAM_REMOTE_NAME=\"default\""

View File

@ -5,3 +5,5 @@ Barry Tulchinsky <barry.tulchinsky@gmail.com> (@btulchinsky)
Kieran Sedgwick <kieran.sedgwick@gmail.com> (@sedge)
Yoav Gurevich <ygurevich@ymail.com>
Gideon Thomas <r.gideonthomas@gmail.com>
Abdirahman Guled <aguled2@myseneca.ca>
Ben Heidemann <ben@heidemann.co.uk>

1
CNAME
View File

@ -1 +0,0 @@
filer.js.org

View File

@ -9,78 +9,67 @@ message and I'll update it.
## Setup
The Filer build system is based on [grunt](http://gruntjs.com/). To get a working build system
do the following:
To get a working build system do the following:
```
npm install
npm install -g grunt-cli
```
You can now run the following grunt tasks:
* `grunt jshint` will run [JSHint](http://www.jshint.com/) on your code (do this before submitting a pull request) to catch errors
* `grunt develop` will create a single file version of the library for testing in `dist/idbfs.js`
* `grunt release` like `develop` but will also create a minified version of the library in `dist/idbfs.min.js`
* `grunt test` or `grunt test-node` will run [JSHint](http://www.jshint.com/) on your code and the test suite in the context of `nodejs`
* `grunt test-browser` will run [JSHint](http://www.jshint.com/) and start a localhost server on port `1234`. Navigating to `localhost:1234/tests/index.html` will run the test suite in the context of the browser. **NOTE:** When finished, you will have to manually shut off the server by pressing `cmd/ctrl`+`c` in the same terminal session you ran `grunt test-browser`.
Next, make sure you have installed Chrome and Firefox, which are needed for
running headless versions of the tests with `npm test`.
Once you've done some hacking and you'd like to have your work merged, you'll need to
make a pull request. If you're patch includes code, make sure to check that all the
unit tests pass, including any new tests you wrote. Finally, make sure you add yourself
to the `AUTHORS` file.
=======
### Releasing a new version
=======
`grunt publish` will:
* Run the `grunt release` task
* Bump `bower.json` & `package.json` version numbers according to a [Semver](http://semver.org/) compatible scheme (see ["How to Publish"](#how-to-publish) below)
* Create a git tag at the new version number
* Create a release commit including `dist/filer.js`, `dist/filer.min.js`, `bower.json` and `package.json`
* Push tag & commit to `origin/develop`
* Update the `gh-pages` branch with the contents of the `develop` branch
* Force push the `gh-pages` branch to `origin/gh-pages`
* Publish the new version of the module to NPM
#### How to configure
1. Copy `env.sample` to `.env`
2. Modify as needed, or leave alone for defaults
#### How to Publish
`grunt publish` can be run in four ways:
1. `grunt publish` - does a patch (x.x.X) bump
2. `grunt publish:patch` - also does a patch (x.x.X) bump
3. `grunt publish:minor` - does a minor (x.X.x) bump
4. `grunt publish:major` - does a major (X.x.x) bump
The user *must* be on their local `develop` branch before running any form of `grunt publish`, or else the task will fail loudly.
=======
## Tests
Tests are writting using [Mocha](http://visionmedia.github.io/mocha/) and [Chai](http://chaijs.com/api/bdd/).
You can run the tests in your browser by running `grunt test-browser` and opening the `tests` directory @ `http://localhost:1234/tests`, or in a nodejs context by running `grunt test`.
Tests are written using [Mocha](https://mochajs.org/) and [Chai](http://chaijs.com/api/bdd/).
There are a number of ways to run the tests. The preferred way is:
```
npm test
```
This will do a build, run the linting, start a server, and load the tests into
headless versions of Chrome and Firefox.
If you want more control over how tests are run, you can use other scripts:
* Linting is done via `npm run lint` or `npm run eslint`, both of which will run `eslint` on the `src` and `tests` directories. You can also use `npm run lint:fix` or `npm run eslint:fix`, which will run `eslint` with `--fix` on the `src` and `tests` directories, automatically fixing minor issues. Linting is run by default as part of `npm test`
* In headless versions of Chrome and Firefox using `npm test`. A report at the end will tell you what happened with each browser. Browser tests are preferred because they also test our providers (e.g., IndexedDB). They do take longer to run. You can also use `npm run karma-mocha-firefox` or `npm run karma-mocha-chrome` to run the tests in only one of the two headless browsers.
* In node.js using the Memory provider using `npm run test:node`. These run much faster, but don't run all tests (e.g., providers, watches).
* If you need to debug browser tests, or want to run them in a different browser, use `npm run test:manual`, which will start a server and you can point your browser to [http://localhost:1234](http://localhost:1234). Running the tests this way will also automatically watch your files, and hot-reload your code and tests, which is useful for debugging and trial/error testing.
* If you need to debug node.js test runs, you can do so using `npm run test:node-debug`. Then, open Chrome and browse to [chrome://inspect](chrome://inspect) and click on your tests in the inspector. The easiest way to get a breakpoint is to manually add a `debugger` keyword to your test code where you want the tests to stop.
> Tip: you can add `skip()` to any `it()` or `describe()` in Mocha to skip a test, or `only()` to have only that test run. For example: `describe.skip(...)` or `it.only(...)`.
* If you want to run migration tests separate from unit tests, use `npm run test:migrations`. Migration tests run at the end of a typical `npm test` run. If you need to create a new migration test, see [`tools/fs-image.js`](tools/fs-image.js) for details on how to generate a filesystem image, and [tests/filesystems/images/README.md](tests/filesystems/images/README.md) for more docs.
* If you want to manually generate coverage info for the tests, use `npm run coverage`. This is done automatically in Travis, so you shouldn't need to do it. You can see [https://codecov.io/gh/filerjs/filer](https://codecov.io/gh/filerjs/filer) for detailed reports.
There are a number of configurable options for the test suite, which are set via query string params.
First, you can choose which filer source to use (i.e., src/, dist/filer-test.js, dist/filer.js or dist/filer.min.js).
The default is to use what is in /dist/filer-test.js, and you can switch to other versions like so:
First, you can choose which filer source to use (i.e., src/, dist/filer-test.js, dist/filer.js or dist/filer.min.js). The default is to use what is in /dist/filer-test.js, and you can switch to other versions like so:
* tests/index.html?filer-dist/filer.js
* tests/index.html?filer-dist/filer.min.js
* tests/index.html?filer-src/filer.js (from src)
Second, you can specify which provider to use for all non-provider specific tests (i.e., most of the tests).
The default provider is `Memory`, and you can switch it like so:
* tests/index.html?filer-provider=memory
* tests/index.html?filer-provider=indexeddb
* tests/index.html?filer-provider=websql
If you're writing tests, make sure you write them in the same style as existing tests, which are
provider agnostic. See `tests/lib/test-utils.js` and how it gets used in various tests as
an example.
provider agnostic. See [`tests/lib/test-utils.js`](tests/lib/test-utils.js) and how it gets used
in various tests as an example.
## Communication
## Releases
If you'd like to talk to someone about the project, you can reach us on irc.mozilla.org in the #filer or #mofodev channel. Look for "ack" or "humph".
In order to perform a release, you'll need commit access to the main Filer repo,
as well as access to publish to Filer's npm module. To do a release:
1. Make sure you have a .env file, with your `GITHUB_TOKEN` included. See [`env.sample`](env.sample) for more info on how to create one.
1. Login to the `npm` registry if you haven't already using `npm login`
1. Run `npm run release`. Releases are done interactively using [release-it](https://www.npmjs.com/package/release-it), and our config is defined in [`.release-it.json`](.release-it.json).

View File

@ -1,4 +1,4 @@
Copyright (c) 2013, Alan Kligman
Copyright (c) 2013 - 2019 Alan Kligman and the Filer contributors
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

603
README.md
View File

@ -1,26 +1,26 @@
[![NPM](https://nodei.co/npm/filer.png?downloads=true&stars=true)](https://nodei.co/npm/filer/)
[![Build Status](https://secure.travis-ci.org/filerjs/filer.png?branch=develop)](http://travis-ci.org/filerjs/filer)
[![Build Status](https://secure.travis-ci.org/filerjs/filer.png?branch=develop)](http://travis-ci.org/filerjs/filer) [![codecov](https://codecov.io/gh/filerjs/filer/branch/master/graph/badge.svg)](https://codecov.io/gh/filerjs/filer)
###Filer
### Filer
Filer is a POSIX-like file system interface for node.js and browser-based JavaScript.
Filer is a drop-in replacement for node's `fs` module, a POSIX-like file system
for browsers.
###Compatibility
### Compatibility
Filer is known to work in the following browsers/versions, with the specified [Storage Providers](#providers):
Filer uses [IndexedDB](https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API)
and is [known to work in the following browsers/versions](https://caniuse.com/#feat=indexeddb):
* node.js: v0.10.*+
* IE: 10+ (IndexedDB)
* Firefox: 26+ (IndexedDB)
* Chrome: 31+ (IndexedDB, WebSQL)
* Safari: 7.0+ (WebSQL)
* Opera: 19+ (IndexedDB, WebSQL)
* iOS: 3.2+ (WebSQL)
* Android Browser: 2.1-4.4 (WebSQL), 4.4+ (IndexedDB)
NOTE: if you're interested in maximum compatibility, use the `Fallback` provider instead of `Default`.
See the section on [Storage Providers](#providers).
* IE: 10+
* Edge: 12+
* Firefox: 10+
* Chrome: 23+
* Safari: 10+
* Opera: 15+
* iOS: 10+
* Android Browser: 4.4+
### Contributing
@ -30,16 +30,15 @@ Want to join the fun? We'd love to have you! See [CONTRIBUTING](https://github.c
Filer can be obtained in a number of ways:
1. npm - `npm install filer`
2. bower - `bower install filer`
3. download pre-built versions: [filer.js](https://raw.github.com/filerjs/filer/develop/dist/filer.js), [filer.min.js](https://raw.github.com/filerjs/filer/develop/dist/filer.min.js)
1. Via npm: `npm install filer`
1. Via unpkg: `<script src="https://unpkg.com/filer"></script>` or specify a version directly, for example: [https://unpkg.com/filer@1.0.1/dist/filer.min.js](https://unpkg.com/filer@1.0.1/dist/filer.min.js)
### Loading and Usage
Filer is built as a UMD module and can therefore be loaded as a CommonJS or AMD module, or used via the global.
```javascript
// Option 1: Filer loaded via require() in node/browserify
// Option 1: Filer loaded via require()
var Filer = require('filer');
// Option 2: Filer loaded via RequireJS
@ -55,13 +54,84 @@ requirejs(['filer'], function(Filer) {...}
var Filer = window.Filer;
```
### Webpack Plugin
Filer can be used as a drop-in replacement for the node.js [fs](http://nodejs.org/api/fs.html) and
[path](http://nodejs.org/api/path.html) modules. For convenience, filer provides a webpack plugin which
will shim the desired node.js functionality. This plugin can be used by inserting the following into
your webpack config:
```javascript
// webpack.config.js
var { FilerWebpackPlugin } = require('filer/webpack');
module.exports = {
plugins: [
new FilerWebpackPlugin(),
],
}
```
---
**NOTE**
Previously it was recommended to access the `FilerWebpackPlugin` class by importing the main filer module. This was depracated due [this issue](https://github.com/filerjs/filer/issues/790). For anyone using ***filer version 1.4.0 or earlier***, please import the plugin class like this:
```javascript
var FilerWebpackPlugin = require('filer/src/webpack-plugin');
```
---
You can then import the node.js [fs](http://nodejs.org/api/fs.html) and [path](http://nodejs.org/api/path.html)
modules as normal and `FilerWebpackPlugin` will ensure that webpack will resolve references to these modules to
the appropriate filer shims. You will then be able to use these modules as normal (with the exception of the
synchronous fs methods e.g. `mkdirSync()`).
```javascript
import fs from 'fs';
import path from 'path';
```
The filer webpack plugin will, by default, shim the [fs](http://nodejs.org/api/fs.html) and
[path](http://nodejs.org/api/path.html) modules. However, it's behaviour can be customised by passing an
options object.
```javascript
// webpack.config.js
module.exports = {
plugins: [
new FilerWebpackPlugin({
// Options
}),
],
}
```
The following options can be passed to the filer webpack plugin:
| Option | Type | Optional | Default | Description |
|---------------|---------|----------|--------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------|
| filerDir | string | yes | '\<rootDir\>/node_modules/filer' | The directory in which filer is installed. |
| shimsDir | string | yes | '\<rootDir\>/node_modules/filer/shims' | The directory in which the shims are installed. |
| fsProviderDir | string | yes | '\<rootDir\>/node_modules/filer/shims/providers' | The directory in which the shims are located. This option is required when using a custom provider. |
| shimFs | boolean | yes | true | Should the fs module be shimmed. |
| shimPath | boolean | yes | true | Should the path module be shimmed. |
| fsProvider | string | yes | 'default' | The file system provider to use. Should be one of 'default', 'indexeddb', 'memory', 'custom'. The 'default' option is equivalent to 'indexeddb'. |
NOTE: '\<rootDir\>' will be resolved to the current working directory.
Though filer also exposes the Buffer object, it is left up to the user to shim this as appropriate. This is because filer offers
no custom implementation. Currently, filer uses the [node-libs-browser](https://github.com/webpack/node-libs-browser) Buffer implementation
internally, though any faithful implementation of the [node.js Buffer object](http://nodejs.org/api/buffer.html) should play nicely
with filer.
### Getting Started
Filer is as close to the node.js [fs module](http://nodejs.org/api/fs.html) as possible,
with the following differences:
* No synchronous versions of methods (e.g., `mkdir()` but not `mkdirSync()`).
* No permissions (e.g., no `chown()`, `chmod()`, etc.).
* No support for stream-based operations (e.g., `fs.ReadStream`, `fs.WriteStream`).
Filer has other features lacking in node.js (e.g., swappable backend
@ -78,18 +148,32 @@ they are invoked. Ensure proper ordering by chaining operations in callbacks.
To create a new file system or open an existing one, create a new `FileSystem`
instance. By default, a new [IndexedDB](https://developer.mozilla.org/en/docs/IndexedDB)
database is created for each file system. The file system can also use other
backend storage providers, for example [WebSQL](http://en.wikipedia.org/wiki/Web_SQL_Database)
or even RAM (i.e., for temporary storage). See the section on [Storage Providers](#providers).
backend storage providers, for example `Memory`. See the section on [Storage Providers](#providers).
```javascript
var fs = new Filer.FileSystem();
fs.open('/myfile', 'w+', function(err, fd) {
if (err) throw err;
fs.close(fd, function(err) {
if (err) throw err;
fs.stat('/myfile', function(err, stats) {
if (err) throw err;
console.log('stats: ' + JSON.stringify(stats));
<a name="overviewExample"></a>
```js
const { fs, path } = require('filer');
fs.mkdir('/docs', (err) => {
if (err) {
return console.error('Unable to create /docs dir', err);
}
const filename = path.join('/docs', 'first.txt');
const data = 'Hello World!\n';
fs.writeFile(filename, data, (err) => {
if (err) {
return console.error('Unable to write /docs/first.txt', err);
}
fs.stat(filename, (err, stats) => {
if (err) {
return console.error('Unable to stat /docs/first.txt', err);
}
console.log('Stats for /docs/first.txt:', stats);
});
});
});
@ -98,7 +182,7 @@ fs.open('/myfile', 'w+', function(err, fd) {
For a complete list of `FileSystem` methods and examples, see the [FileSystem Instance Methods](#FileSystemMethods)
section below.
Filer also supports node's Path module. See the [Filer.Path](#FilerPath) section below.
Filer also includes node's `path` and `Buffer` modules. See the [Filer.Path](#FilerPath) and [Filer.Buffer](#FilerBuffer) sections below.
In addition, common shell operations (e.g., rm, touch, cat, etc.) are supported via the
`FileSystemShell` object, which can be obtained from, and used with a `FileSystem`.
@ -110,11 +194,29 @@ Like node.js, callbacks for methods that accept them are optional but suggested
you omit the callback, errors will be thrown as exceptions). The first callback parameter is
reserved for passing errors. It will be `null` if no errors occurred and should always be checked.
#### Support for Promises
The Promise based API mimics the way node [implements](https://nodejs.org/api/fs.html#fs_fs_promises_api) them. Both `Shell` and `FileSystem` now have a `promises` property, which gives access to Promise based versions of methods in addition to the regular callback style methods. Method names are identical to their callback counterparts with the difference that instead of receiving a final argument as a callback, they return a Promise that is resolved or rejected based on the success of method execution.
See example below:
```javascript
const fs = new Filer.FileSystem().promises;
fs.writeFile('/myfile', 'some data')
.then(() => fs.stat('/myfile'))
.then(stats => { console.log(`stats: ${JSON.stringify(stats)}`); })
.catch(err => { console.error(err); });
```
#### Filer.FileSystem(options, callback) constructor
File system constructor, invoked to open an existing file system or create a new one.
Accepts two arguments: an `options` object, and an optional `callback`. The `options`
object can specify a number of optional arguments, including:
In most cases, using `Filer.fs` will be sufficient, and provide a working filesystem.
However, if you need more control over the filesystem, you can also use the `FileSystem`
constructor, invoked to open an existing file system or create a new one.
`Filer.FileSystem()` It accepts two arguments: an `options` object, and an optional
`callback` function. The `options` object can specify a number of optional arguments,
including:
* `name`: the name of the file system, defaults to `'"local'`
* `flags`: an Array of one or more flags to use when creating/opening the file system:
@ -147,17 +249,19 @@ NOTE: if the optional callback argument is not passed to the `FileSystem` constr
operations done on the resulting file system will be queued and run in sequence when
it becomes ready.
####Filer.FileSystem.providers - Storage Providers<a name="providers"></a>
#### Filer.FileSystem.providers - Storage Providers<a name="providers"></a>
Filer can be configured to use a number of different storage providers. The provider object encapsulates all aspects
of data access, making it possible to swap in different backend storage options. There are currently 4 different
providers to choose from:
Filer can be configured to use a number of different storage providers. The provider object encapsulates all aspects of data access, making it possible to swap in different backend storage options. There are currently 2 providers to choose from:
* `FileSystem.providers.IndexedDB()` - uses IndexedDB
* `FileSystem.providers.WebSQL()` - uses WebSQL
* `FileSystem.providers.Fallback()` - attempts to use IndexedDB if possible, falling-back to WebSQL if necessary
if necessary
* `FileSystem.providers.Memory()` - uses memory (not suitable for data that needs to survive the current session)
**NOTE**: previous versions of Filer also supported `FileSystem.providers.WebSQL()` and
`FileSystem.providers.Fallback()`, which could be used in browsers that supported
WebSQL but not IndexedDB. [WebSQL has been deprecated](https://www.w3.org/TR/webdatabase/),
and this functionality was removed in `v1.0.0`. If for some reason you still need it, use [`v0.0.44`](https://github.com/filerjs/filer/releases/tag/v0.0.44).
You can choose your provider when creating a `FileSystem`:
```javascript
@ -167,45 +271,62 @@ var providers = FileSystem.providers;
// Example 1: Use the default provider (currently IndexedDB)
var fs1 = new FileSystem();
// Example 2: Explicitly use IndexedDB
var fs2 = new FileSystem({ provider: new providers.IndexedDB() });
// Example 3: Use one of IndexedDB or WebSQL, whichever is supported
var fs3 = new FileSystem({ provider: new providers.Fallback() });
// Example 2: Use the Memory provider
var fs2 = new FileSystem({ provider: new providers.Memory() });
```
Every provider has an `isSupported()` method, which returns `true` if the browser supports this provider:
```javascript
if( Filer.FileSystem.providers.WebSQL.isSupported() ) {
// WebSQL provider will work in current environment...
if( Filer.FileSystem.providers.IndexedDB.isSupported() ) {
// IndexedDB provider will work in current environment...
}
```
You can also write your own provider if you need a different backend. See the code in `src/providers` for details.
A number of other providers have been written, including:
* node.js fs provider: https://github.com/humphd/filer-fs
* node.js Amazon S3 provider: https://github.com/alicoding/filer-s3
####Filer.Buffer<a name="FilerBuffer"></a>
#### Filer.Buffer<a name="FilerBuffer"></a>
When reading and writing data, Filer follows node.js and uses [`Buffer`](http://nodejs.org/api/buffer.html).
When in a node.js environment, native `Buffer`s can be used, or Filer.Buffer, which is a shortcut
to node's `Buffer`. In a browser, you can use also use `Filer.Buffer`.
NOTE: a `Filer.Buffer` in a browser is really an augmented `Uint8Array` (i.e., the node `Buffer` api
methods are added to the instance). See https://github.com/feross/buffer for more details. Additionally, unlike native `Buffer`, `Filer.Buffer`'s constructor can accept `ArrayBuffer` objects, which will be interpreted as `Uint8Array`s.
methods are added to the instance). See https://github.com/feross/buffer for more details.
####Filer.Path<a name="FilerPath"></a>
NOTE: `Filer.Buffer` currently includes the older, deprecated [constructor functions](https://nodejs.org/api/buffer.html#buffer_new_buffer_array), but these will be removed
at some point. You are encouraged to switch to use the newer class methods `Buffer.from()`
and `Buffer.alloc()`. See the [node.js Buffer docs](https://nodejs.org/api/buffer.html).
The node.js [path module](http://nodejs.org/api/path.html) is available via the `Filer.Path` object. It is
identical to the node.js version with the following differences:
* No notion of a current working directory in `resolve` (the root dir is used instead)
```js
/* Deprecated - see https://nodejs.org/api/buffer.html#buffer_new_buffer_array */
new Buffer(array)
new Buffer(arrayBuffer[, byteOffset[, length]])
new Buffer(buffer)
new Buffer(string[, encoding])
new Buffer(size)
/* Use Instead */
Buffer.from(array)
Buffer.from(arrayBuffer[, byteOffset[, length]])
Buffer.from(buffer)
Buffer.from(string[, encoding])
Buffer.alloc(size)
Buffer.allocUnsafe(size)
```
#### Filer.Path<a name="FilerPath"></a>
The node.js [path module](http://nodejs.org/api/path.html) is available via `Filer.path` or
`Filer.Path` (both are supported for historical reasons, and to match node). The Filer `path`
module is identical to the node.js version (see [https://github.com/browserify/path-browserify](https://github.com/browserify/path-browserify)), with the following differences:
* The CWD always defaults to `/`
* No support for Windows style paths (assume you are on a POSIX system)
* Additional utility methods (see below)
```javascript
var path = Filer.Path;
var path = Filer.path;
var dir = path.dirname('/foo/bar/baz/asdf/quux');
// dir is now '/foo/bar/baz/asdf'
@ -220,17 +341,38 @@ var newpath = path.join('/foo', 'bar', 'baz/asdf', 'quux', '..');
```
For more info see the docs in the [path module](http://nodejs.org/api/path.html) for a particular method:
* `path.normalize(p)`
* `path.normalize(p)` - NOTE: Filer.Path.normalize does *not* add a trailing slash
* `path.join([path1], [path2], [...])`
* `path.resolve([from ...], to)`
* `path.relative(from, to)`
* `path.dirname(p)`
* `path.basename(p, [ext])`
* `path.basename(p, [ext])` - NOTE: Filer.Path.basename will return `'/'` vs. `''`
* `path.extname(p)`
* `path.sep`
* `path.delimiter`
####Filer.Errors<a name="Errors"></a>
Filer.Path also includes the following extra methods:
* `isNull(p)` returns `true` or `false` if the path contains a null character (`'\u0000'`)
* `addTrailing(p)` returns the path `p` with a single trailing slash added
* `removeTrailing(p)` returns the path `p` with trailing slash(es) removed
[As with node.js](https://nodejs.org/api/fs.html#fs_file_paths), all methods below that
accept a `path` argument as a `String` can also take a [`file://` URL](https://nodejs.org/api/fs.html#fs_url_object_support)
or a `Buffer`. For example, all of the following cases will work the same way with Filer:
```js
// 1. path as a String
fs.writeFile('/dir/file.txt', 'data', function(err) {...});
// 2. path as a URL
fs.writeFile(new URL('file:///dir/file.txt'), 'data', function(err) {...});
// 3. path as a Buffer
fs.writeFile(Buffer.from('/dir/file.txt'), 'data', function(err) {...});
```
#### Filer.Errors<a name="Errors"></a>
The error objects used internally by Filer are also exposed via the `Filer.Errors` object. As much as possible
these match their node.js counterparts, with a few Filer-specifc additions.
@ -266,13 +408,17 @@ function callback(err) {
console.log(err.message);
```
###FileSystem Instance Methods<a name="FileSystemMethods"></a>
### FileSystem Instance Methods<a name="FileSystemMethods"></a>
Once a `FileSystem` is created, it has the following methods. NOTE: code examples below assume
a `FileSystem` instance named `fs` has been created like so:
```javascript
var fs = new Filer.FileSystem();
// 1. Using Filer.fs for a default filesystem
const { fs } = require('filer');
// 2. Or via the FileSystem constructor with specified options
const fs = new Filer.FileSystem(options, callback);
```
* [fs.rename(oldPath, newPath, callback)](#rename)
@ -290,10 +436,16 @@ var fs = new Filer.FileSystem();
* [fs.mknod(path, mode, callback)](#mknod)
* [fs.rmdir(path, callback)](#rmdir)
* [fs.mkdir(path, [mode], callback)](#mkdir)
* [fs.access(path, [mode], callback)](#access)
* [fs.mkdtemp(path, [options], callback)](#mkdtemp)
* [fs.readdir(path, callback)](#readdir)
* [fs.close(fd, callback)](#close)
* [fs.open(path, flags, [mode], callback)](#open)
* [fs.utimes(path, atime, mtime, callback)](#utimes)
* [fs.chown(path, uid, gid, callback)](#chown)
* [fs.fchown(fd, uid, gid, callback)](#fchown)
* [fs.chmod(path, mode, callback)](#chmod)
* [fs.fchmod(fd, mode, callback)](#fchmod)
* [fs.futimes(fd, atime, mtime, callback)](#fsutimes)
* [fs.fsync(fd, callback)](#fsync)
* [fs.write(fd, buffer, offset, length, position, callback)](#write)
@ -335,7 +487,7 @@ Example:
```javascript
// Create a file, shrink it, expand it.
var buffer = new Filer.Buffer([1, 2, 3, 4, 5, 6, 7, 8]);
var buffer = Filer.Buffer.from([1, 2, 3, 4, 5, 6, 7, 8]);
fs.open('/myfile', 'w', function(err, fd) {
if(err) throw error;
@ -366,7 +518,7 @@ Example:
```javascript
// Create a file, shrink it, expand it.
var buffer = new Filer.Buffer([1, 2, 3, 4, 5, 6, 7, 8]);
var buffer = Filer.Buffer.from([1, 2, 3, 4, 5, 6, 7, 8]);
fs.open('/myfile', 'w', function(err, fd) {
if(err) throw error;
@ -397,14 +549,22 @@ Callback gets `(error, stats)`, where `stats` is an object with the following pr
```
{
node: <string> // internal node id (unique)
dev: <string> // file system name
size: <number> // file size in bytes
nlinks: <number> // number of links
atime: <number> // last access time
mtime: <number> // last modified time
ctime: <number> // creation time
type: <string> // file type (FILE, DIRECTORY, SYMLINK)
node: <string> // internal node id (unique)
dev: <string> // file system name
name: <string> // the entry's name (basename)
size: <number> // file size in bytes
nlinks: <number> // number of links
atime: <date> // last access time as JS Date Object
mtime: <date> // last modified time as JS Date Object
ctime: <date> // creation time as JS Date Object
atimeMs: <number> // last access time as Unix Timestamp
mtimeMs: <number> // last modified time as Unix Timestamp
ctimeMs: <number> // creation time as Unix Timestamp
type: <string> // file type (FILE, DIRECTORY, SYMLINK),
gid: <number> // group name
uid: <number> // owner name
mode: <number> // permissions
version: <number> // version of the node
}
```
@ -498,8 +658,8 @@ fs.link("/data/logs/august", "/data/logs/current", function(err) {
#### fs.exists(path, callback)<a name="exists"></a>
Test whether or not the given path exists by checking with the file system.
Then call the callback argument with either true or false.
Test whether or not the given path exists by checking with the file system.
Then call the callback argument with either true or false.
Example:
@ -536,10 +696,12 @@ Create a symbolic link to the file at `dstPath` containing the path `srcPath`. A
Symbolic links are files that point to other paths.
NOTE: Filer allows for, but ignores the optional `type` parameter used in node.js.
The `srcPath` may be a relative path, which will be resolved relative to `dstPath`
Example:
```javascript
// Absolute path
fs.symlink('/logs/august.log', '/logs/current', function(err) {
if(err) throw err;
fs.readFile('/logs/current', 'utf8', function(err, data) {
@ -547,11 +709,21 @@ fs.symlink('/logs/august.log', '/logs/current', function(err) {
var currentLog = data;
});
});
// Relative path
fs.symlink('../file', '/dir/symlink', function(err) {
if(err) throw err;
// The /dir/symlink file is now a symlink to /file
});
```
#### fs.readlink(path, callback)<a name="readlink"></a>
Reads the contents of a symbolic link. Asynchronous [readlink(2)](http://pubs.opengroup.org/onlinepubs/009695399/functions/readlink.html). Callback gets `(error, linkContents)`, where `linkContents` is a string containing the symbolic link's link path.
Reads the contents of a symbolic link. Asynchronous [readlink(2)](http://pubs.opengroup.org/onlinepubs/009695399/functions/readlink.html).
Callback gets `(error, linkContents)`, where `linkContents` is a string
containing the symbolic link's link path. If the original `srcPath` given
to `symlink()` was a relative path, it will be fully resolved relative
to `dstPath` when returned by `readlink()`.
Example:
@ -596,7 +768,7 @@ Example:
fs.mknod('/dir', 'DIRECTORY', function(err) {
if(err) throw err;
// /dir is now created
// Create a file inside /dir
fs.mknod('/dir/myfile', 'FILE', function(err) {
if(err) throw err;
@ -648,7 +820,47 @@ fs.mkdir('/home', function(err) {
});
```
#### fs.readdir(path, callback)<a name="readdir"></a>
#### fs.access(path, [mode], callback)<a name="access"></a>
Tests a user's permissions for the file or directory supplied in `path` argument. Asynchronous [access(2)](http://pubs.opengroup.org/onlinepubs/009695399/functions/access.html). Callback gets no additional arguments. The `mode` argument can be one of the following (constants are available on `fs.constants` and `fs`):
* `F_OK`: Test for existence of file.
* `R_OK`: Test whether the file exists and grants read permission.
* `W_OK`: Test whether the file exists and grants write permission.
* `X_OK`: Test whether the file exists and grants execute permission.
NOTE: you can also create a mask consisting of the bitwise OR of two or more values (e.g. `fs.constants.W_OK | fs.constants.R_OK`).
Example:
```javascript
// Check if the file exists in the current directory.
fs.access(file, fs.F_OK, function(err) {
console.log(`${file} ${err ? 'does not exist' : 'exists'}`);
});
```
#### fs.mkdtemp(prefix, options, callback)<a name="mkdtemp"></a>
Makes a temporary directory with prefix supplied in `path` argument. Method will append six random characters directly to the prefix. Asynchronous. Callback gets `(error, path)`, where path is the path to the created directory.
NOTE: Filer allows for, but ignores the optional `options` argument used in node.js.
Example:
```javascript
// Create tmp directory with prefix foo
fs.mkdtemp("/foo-", function (error, path) {
// A new folder foo-xxxxxx will be created. Path contains a path to created folder.
});
fs.mkdtemp("/myDir/tmp", function (error, path) {
// Will create a new folder tmpxxxxxx inside myDir directory.
// Will throw error if myDir does not exist
});
```
#### fs.readdir(path, [options], callback)<a name="readdir"></a>
Reads the contents of a directory. Asynchronous [readdir(3)](http://pubs.opengroup.org/onlinepubs/009695399/functions/readdir.html).
Callback gets `(error, files)`, where `files` is an array containing the names of each directory entry (i.e., file, directory, link) in the directory, excluding `.` and `..`.
@ -669,6 +881,12 @@ fs.readdir('/docs', function(err, files) {
});
```
Optionally accepts an options parameter, which can be either an encoding (e.g. "utf8") or an object with optional properties `encoding` and `withFileTypes`.
The `encoding` property is a `string` which will determine the character encoding to use for the names of each directory entry. The `withFileTypes` property is a `boolean` which defaults to `false`. If `true`, this method will return an array of [fs.Dirent](https://nodejs.org/api/fs.html#fs_class_fs_dirent) objects.
The `name` property on the [fs.Dirent](https://nodejs.org/api/fs.html#fs_class_fs_dirent) objects will be encoded using the specified character encoding.
#### fs.close(fd, callback)<a name="close"></a>
Closes a file descriptor. Asynchronous [close(2)](http://pubs.opengroup.org/onlinepubs/009695399/functions/close.html).
@ -716,7 +934,7 @@ fs.open('/myfile', 'w', function(err, fd) {
#### fs.utimes(path, atime, mtime, callback)<a name="utimes"></a>
Changes the file timestamps for the file given at path `path`. Asynchronous [utimes(2)](http://pubs.opengroup.org/onlinepubs/009695399/functions/utimes.html). Callback gets no additional arguments. Both `atime` (access time) and `mtime` (modified time) arguments should be a JavaScript Date.
Changes the file timestamps for the file given at path `path`. Asynchronous [utimes(2)](http://pubs.opengroup.org/onlinepubs/009695399/functions/utimes.html). Callback gets no additional arguments. Both `atime` (access time) and `mtime` (modified time) arguments should be a JavaScript Date or Number.
Example:
@ -730,7 +948,7 @@ fs.utimes('/myfile.txt', now, now, function(err) {
#### fs.futimes(fd, atime, mtime, callback)<a name="futimes"></a>
Changes the file timestamps for the open file represented by the file descriptor `fd`. Asynchronous [utimes(2)](http://pubs.opengroup.org/onlinepubs/009695399/functions/utimes.html). Callback gets no additional arguments. Both `atime` (access time) and `mtime` (modified time) arguments should be a JavaScript Date.
Changes the file timestamps for the open file represented by the file descriptor `fd`. Asynchronous [utimes(2)](http://pubs.opengroup.org/onlinepubs/009695399/functions/utimes.html). Callback gets no additional arguments. Both `atime` (access time) and `mtime` (modified time) arguments should be a JavaScript Date or Number.
Example:
@ -749,9 +967,107 @@ fs.open('/myfile.txt', function(err, fd) {
});
```
#### fs.chown(path, uid, gid, callback)<a name="chown"></a>
Changes the owner and group of a file. Asynchronous [chown(2)](http://pubs.opengroup.org/onlinepubs/009695399/functions/chown.html). Callback gets no additional arguments. Both `uid` (user id) and `gid` (group id) arguments should be a JavaScript Number. By default, `0x0` is used (i.e., `root:root` ownership).
Example:
```javascript
fs.chown('/myfile.txt', 500, 500, function(err) {
if(err) throw err;
// /myfile.txt is now owned by user with id 500, group 500
});
```
#### fs.fchown(fd, uid, gid, callback)<a name="fchown"></a>
Changes the owner and group of a file. Asynchronous [chown(2)](http://pubs.opengroup.org/onlinepubs/009695399/functions/chown.html). Callback gets no additional arguments. Both `uid` (user id) and `gid` (group id) arguments should be a JavaScript Number. By default, `0x0` is used (i.e., `root:root` ownership).
Example:
```javascript
fs.open('/myfile.txt', function(err, fd) {
if(err) throw err;
fs.fchown(fd, 500, 500, function(err) {
if(err) throw err;
// /myfile.txt is now owned by user with id 500, group 500
fs.close(fd);
});
});
```
#### fs.chmod(path, mode, callback)<a name="chmod"></a>
Changes the mode of a file. Asynchronous [chmod(2)](http://pubs.opengroup.org/onlinepubs/009695399/functions/chmod.html). Callback gets no additional arguments. The `mode` argument should be a JavaScript Number, which combines file type and permission information. Here are a list of common values useful for setting the `mode`:
* File type `S_IFREG=0x8000`
* Dir type `S_IFDIR=0x4000`
* Link type `S_IFLNK=0xA000`
* Permissions `755=0x1ED`
* Permissions `644=0x1A4`
* Permissions `777=0x1FF`
* Permissions `666=0x1B6`
By default, directories use `(0x4000 | 0x1ED)` and files use `(0x8000 | 0x1A4)`.
Example:
```javascript
// S_IFREG | 0o777
var mode = 0x8000 | 0x1FF
fs.chmod('/myfile.txt', mode, function(err) {
if(err) throw err;
// /myfile.txt is a regular file with permissions 777
});
```
#### fs.fchmod(fd, mode, callback)<a name="fchmod"></a>
Changes the mode of a file. Asynchronous [chmod(2)](http://pubs.opengroup.org/onlinepubs/009695399/functions/chmod.html). Callback gets no additional arguments. The `mode` argument should be a JavaScript Number, which combines file type and permission information. By default, `755` (dir) and `644` (file) are used.
Example:
```javascript
fs.open('/myfile.txt', function(err, fd) {
if(err) throw err;
// S_IFREG | 0o777
var mode = 0x8000 | 0x1FF
fs.fchmod(fd, mode, function(err) {
if(err) throw err;
// /myfile.txt is a regular file with permissions 777
fs.close(fd);
});
});
```
#### fs.fsync(fd, callback)<a name="fsync"></a>
NOTE: Not yet implemented, see https://github.com/filerjs/filer/issues/87
Synchronize the data and metadata for the file referred to by `fd` to disk.
Asynchronous [fsync(2)](http://man7.org/linux/man-pages/man2/fsync.2.html).
The callback gets `(error)`.
```js
fs.open('/myfile', 'r', function(error, fd) {
if(err) throw err;
// Use fd, then sync
fs.fsync(fd, function(error) {
if(err) throw err;
fs.close(fd, done);
});
});
```
#### fs.write(fd, buffer, offset, length, position, callback)<a name="write"></a>
@ -763,7 +1079,7 @@ Example:
```javascript
// Create a file with the following bytes.
var buffer = new Filer.Buffer([1, 2, 3, 4, 5, 6, 7, 8]);
var buffer = Filer.Buffer.from([1, 2, 3, 4, 5, 6, 7, 8]);
fs.open('/myfile', 'w', function(err, fd) {
if(err) throw error;
@ -800,22 +1116,22 @@ Example:
```javascript
fs.open('/myfile', 'r', function(err, fd) {
if(err) throw error;
if(err) throw err;
// Determine size of file
fs.fstat(fd, function(err, stats) {
if(err) throw error;
if(err) throw err;
// Create a buffer large enough to hold the file's contents
var nbytes = expected = stats.size;
var buffer = new Filer.Buffer(nbytes);
var buffer = Filer.Buffer.alloc(nbytes);
var read = 0;
function readBytes(offset, position, length) {
length = length || buffer.length - read;
fs.read(fd, buffer, offset, length, position, function(err, nbytes) {
if(err) throw error;
if(err) throw err;
// nbytes is now the number of bytes read, between 0 and buffer.length.
// See if we still have more bytes to read.
@ -866,7 +1182,7 @@ fs.writeFile('/myfile.txt', "...data...", function (err) {
});
// Write binary file
var buffer = new Filer.Buffer([1, 2, 3, 4, 5, 6, 7, 8]);
var buffer = Filer.Buffer.from([1, 2, 3, 4, 5, 6, 7, 8]);
fs.writeFile('/myfile', buffer, function (err) {
if (err) throw err;
});
@ -889,15 +1205,15 @@ fs.appendFile('/myfile.txt', "Data...", function (err) {
// '/myfile.txt' would now read out 'More...Data...'
// Append binary file
var data = new Filer.Buffer([1, 2, 3, 4]);
var more = new Filer.Buffer([5, 6, 7, 8]);
var data = Filer.Buffer.from([1, 2, 3, 4]);
var more = Filer.Buffer.from([5, 6, 7, 8]);
fs.writeFile('/myfile', data, function (err) {
if (err) throw err;
fs.appendFile('/myfile', more, function (err) {
if (err) throw err;
// '/myfile' would now contain [1, 2, 3, 4, 5, 6, 7, 8]
});
});
@ -1088,20 +1404,31 @@ fs.writeFile('/data/subdir/file', 'data');
### FileSystemShell<a name="FileSystemShell"></a>
Many common file system shell operations are available by using a `FileSystemShell` object.
The `FileSystemShell` is obtained from, and used in conjuction with a `FileSystem`,
The `FileSystemShell` is used in conjunction with a `FileSystem`,
and provides augmented features. Many separate `FileSystemShell` objects can exist per
`FileSystem`, but each `FileSystemShell` is bound to a single instance of a `FileSystem`
for its lifetime.
A `FileSystemShell` is created using the `FileSystem.Shell()` function:
A `FileSystemShell` is created by instantiating `Filer.FileSystem().Shell`:
```javascript
var fs = new Filer.FileSystem();
var sh = fs.Shell(options);
var sh2 = fs.Shell(options);
var sh = new fs.Shell(options);
var sh2 = new fs.Shell(options);
// sh and sh2 are two separate shells, each bound to fs
```
In addition, the constructor function can be accessed through `Filer`:
```javascript
var fs = new Filer.FileSystem();
var sh = new fs.Shell();
Filer.Shell.prototype.newFunction = ...;
sh.newFunction();
```
The `FileSystemShell` can take an optional `options` object. The `options` object
can include `env`, which is a set of environment variables. Currently supported variables
include `TMP` (the path to the temporary directory), and `PATH` (the list of known paths) and
@ -1109,7 +1436,7 @@ others may be added in the future. You can also add your own, or update existing
```javascript
var fs = new Filer.FileSystem();
var sh = fs.Shell({
var sh = new fs.Shell({
env: {
TMP: '/tempdir',
PATH: '/one:/two'
@ -1135,7 +1462,7 @@ Example:
```javascript
var fs = new Filer.FileSystem();
var sh = fs.Shell();
var sh = new fs.Shell();
var p = sh.env.get('PATH');
// Store the current location
@ -1155,11 +1482,12 @@ examples below assume a `FileSystemShell` instance named `sh` has been created l
```javascript
var fs = new Filer.FileSystem();
var sh = fs.Shell();
var sh = new fs.Shell();
```
* [sh.cd(path, callback)](#cd)
* [sh.pwd()](#pwd)
* [sh.find(dir, [options], callback)](#find)
* [sh.ls(dir, [options], callback)](#ls)
* [sh.exec(path, [args], callback)](#exec)
* [sh.touch(path, [options], callback)](#touch)
@ -1188,20 +1516,71 @@ sh.cd('/dir1', function(err) {
Returns the shell's current working directory. See [sh.cd()](#cd).
#### sh.find(dir, [options], callback)<a name="find"></a>
Recursively walk a directory tree, reporting back all paths that were
found along the way. Asynchronous [find(1)](http://pubs.opengroup.org/onlinepubs/9699919799/utilities/find.html
)
If given no options, `find` walks the given dir path
and the callback gives `function(err, found)`, where `found` is an array of
all paths discovered during a depth-first walk.
Valid options include a `regex` for pattern matching paths, allowing paths
to be ignored (e.g., ```regex: /\.bak$/``` to find all `.bak` files). You can
also use `name` and `path` to provide a [match pattern](https://github.com/isaacs/minimatch) for the basename and
dirname respectively (e.g., `{name: '*.js'}` to find all JavaScript files or
`{path: '*-modules'}` to only look in folders named `base-modules`, `foo-modules`, etc.).
Finally, you can also provide an `exec` function of the form `function(path, next)` where
`path` is the current path that was found and matches any provided `regex`
(NOTE: dir paths have an '/' appended), and `next` is a callback to call
when you are done processing the path.
Example:
```javascript
function processPath(path, next) {
// Process the path somehow, in this case we print it.
// Dir paths end with /
if(path.endsWith('/')) {
console.log('Found dir: ' + path);
} else {
console.log('Found file: ' + path);
}
// All done, let the process continue by invoking second arg:
next();
}
// Get every path (NOTE: no name or regex provided) below the root, depth first
sh.find('/', {exec: processPath}, function(err, found) {
/* find command is finished, `found` contains the flattened list as an Array */
});
// Find all files that look like map201.jpg, map202.jpg in the /data dir
sh.find('/data', {regex: /map20\d\.jpg$/, exec: processPath}, function(err) {
/* find command is finished */
});
// Find and delete all *.bak files under /app/user
sh.find('/app/user', {
name: '*.bak',
exec: function(path, next) {
sh.rm(path, next);
}
}, function callback(err, found) {
if(err) throw err;
if(found.length) {
console.log('Deleted the following ' + found.length + ' files: ', found);
}
});
```
#### sh.ls(dir, [options], callback)<a name="ls"></a>
Get the listing of a directory, returning an array of directory entries
in the following form:
```
{
path: <String> the basename of the directory entry
links: <Number> the number of links to the entry
size: <Number> the size in bytes of the entry
modified: <Number> the last modified date/time
type: <String> the type of the entry
contents: <Array> an optional array of child entries, if this entry is itself a directory
}
```
in the same form as [fs.stat()](#stat), with the exception that a new Array named
`contents` is added for directory entries, containing child entries.
By default `sh.ls()` gives a shallow listing. If you want to follow
directories as they are encountered, use the `recursive=true` option. NOTE:
@ -1360,9 +1739,9 @@ sh.tempDir(function(err, tmp) {
#### sh.mkdirp(path, callback)<a name="mkdirp"></a>
Recursively creates the directory at the provided path. If the
Recursively creates the directory at the provided path. If the
directory already exists, no error is returned. All parents must
be valid directories (not files).
be valid directories (not files).
Example:

View File

@ -1,15 +0,0 @@
{
"name": "filer",
"version": "0.0.35",
"main": "dist/filer.js",
"ignore": [
"build",
"examples",
"package.json",
"tests",
"gruntfile.js",
"node_modules",
"src",
"tools"
]
}

View File

@ -1,5 +0,0 @@
module.exports = (function() {
var habitat = require('habitat');
habitat.load();
return new habitat();
})();

10075
dist/filer-perf.js vendored

File diff suppressed because it is too large Load Diff

20700
dist/filer-test.js vendored

File diff suppressed because it is too large Load Diff

24659
dist/filer.js vendored

File diff suppressed because it is too large Load Diff

1
dist/filer.js.map vendored Normal file

File diff suppressed because one or more lines are too long

1
dist/filer.map vendored Normal file

File diff suppressed because one or more lines are too long

253
dist/filer.min.js vendored

File diff suppressed because one or more lines are too long

1
dist/filer.min.js.map vendored Normal file

File diff suppressed because one or more lines are too long

1
dist/filer.min.map vendored Normal file

File diff suppressed because one or more lines are too long

View File

@ -1,14 +1,9 @@
###
# Dev ENVIRONMENT file
#
# Copy to .env to use defaults
# Copy to .env to use defaults when releasing via `npm release`
###
# GIT (upstream) url to publish to
export FILER_UPSTREAM_URI="git@github.com:js-platform/filer.git"
# GIT (upstream) branch to publish to
export FILER_UPSTREAM_BRANCH="develop"
# Remote name for upstream repo
export FILER_UPSTREAM_REMOTE_NAME="origin"
# GitHub Personal Access Token (to push releases)
# https://help.github.com/articles/creating-a-personal-access-token-for-the-command-line/
GITHUB_TOKEN=

View File

@ -1,231 +0,0 @@
var semver = require('semver'),
fs = require('fs'),
currentVersion = JSON.parse(fs.readFileSync('./package.json', 'utf8')).version,
env = require('./config/environment');
// Globals
var PROMPT_CONFIRM_CONFIG = 'confirmation',
GIT_BRANCH = env.get('FILER_UPSTREAM_BRANCH'),
GIT_REMOTE = env.get('FILER_UPSTREAM_REMOTE_NAME'),
GIT_FULL_REMOTE = env.get('FILER_UPSTREAM_URI') + ' ' + GIT_BRANCH;
module.exports = function(grunt) {
// Project configuration.
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
clean: ['dist/filer-test.js', 'dist/filer-issue225.js'],
uglify: {
options: {
banner: '/*! <%= pkg.name %> <%= pkg.version %> <%= grunt.template.today("yyyy-mm-dd") %> */\n'
},
develop: {
src: 'dist/filer.js',
dest: 'dist/filer.min.js'
}
},
jshint: {
// Don't bother with src/path.js
all: [
'gruntfile.js',
'config/environment.js',
'src/constants.js',
'src/errors.js',
'src/fs.js',
'src/index.js',
'src/shared.js',
'src/shell.js',
'src/fswatcher.js',
'src/environment.js',
'src/providers/**/*.js',
'src/adapters/**/*.js',
'src/directory-entry.js',
'src/open-file-description.js',
'src/super-node.js',
'src/node.js',
'src/stats.js',
'src/filesystem/**/*.js'
]
},
browserify: {
filerDist: {
src: "./src/index.js",
dest: "./dist/filer.js",
options: {
browserifyOptions: {
commondir: false
},
bundleOptions: {
standalone: 'Filer'
},
exclude: ["./node_modules/request/index.js"]
}
},
filerTest: {
src: "./tests/index.js",
dest: "./dist/filer-test.js"
},
// See tests/bugs/issue225.js
filerIssue225: {
src: "./src/index.js",
dest: "./dist/filer-issue225.js",
options: {
browserifyOptions: {
commondir: false
},
bundleOptions: {
standalone: 'Filer'
}
}
}
},
shell: {
mocha: {
// Run all tests (e.g., tests require()'ed in tests/index.js) and also tests/bugs/issue225.js
// separately, since it can't be included in a browserify build.
command: '"./node_modules/.bin/mocha" --reporter list tests/index.js && "./node_modules/.bin/mocha" --reporter list tests/bugs/issue225.js'
}
},
bump: {
options: {
files: ['package.json', 'bower.json'],
commit: true,
commitMessage: 'v%VERSION%',
commitFiles: ['package.json', 'bower.json', './dist/filer.js', './dist/filer.min.js', './dist/filer-test.js'],
createTag: true,
tagName: 'v%VERSION%',
tagMessage: 'v%VERSION%',
push: true,
pushTo: GIT_FULL_REMOTE
}
},
'npm-checkBranch': {
options: {
branch: GIT_BRANCH
}
},
'npm-publish': {
options: {
abortIfDirty: false
}
},
prompt: {
confirm: {
options: {
questions: [
{
config: PROMPT_CONFIRM_CONFIG,
type: 'confirm',
message: 'Bump version from ' + (currentVersion).cyan +
' to ' + semver.inc(currentVersion, "patch").yellow + '?',
default: false
}
],
then: function(results) {
if (!results[PROMPT_CONFIRM_CONFIG]) {
return grunt.fatal('User aborted...');
}
}
}
}
},
gitcheckout: {
publish: {
options: {
branch: 'gh-pages',
overwrite: true
}
},
revert: {
options: {
branch: GIT_BRANCH
}
}
},
gitpush: {
publish: {
options: {
remote: GIT_REMOTE,
branch: 'gh-pages',
force: true
},
}
},
connect: {
serverForNode: {
options: {
port: 1234,
base: '.'
}
},
serverForBrowser: {
options: {
port: 1234,
base: '.',
keepalive: true
}
}
}
});
grunt.loadNpmTasks('grunt-contrib-clean');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-connect');
grunt.loadNpmTasks('grunt-bump');
grunt.loadNpmTasks('grunt-npm');
grunt.loadNpmTasks('grunt-git');
grunt.loadNpmTasks('grunt-prompt');
grunt.loadNpmTasks('grunt-shell');
grunt.loadNpmTasks('grunt-contrib-connect');
grunt.loadNpmTasks('grunt-browserify');
grunt.registerTask('develop', ['clean', 'browserify']);
grunt.registerTask('build-tests', ['clean', 'browserify:filerTest']);
grunt.registerTask('release', ['test', 'develop', 'uglify']);
grunt.registerTask('publish', 'Publish filer as a new version to NPM, bower and github.', function(patchLevel) {
var allLevels = ['patch', 'minor', 'major'];
// No level specified defaults to 'patch'
patchLevel = (patchLevel || 'patch').toLowerCase();
// Fail out if the patch level isn't recognized
if (allLevels.filter(function(el) { return el == patchLevel; }).length === 0) {
return grunt.fatal('Patch level not recognized! "Patch", "minor" or "major" only.');
}
// Set prompt message
var promptOpts = grunt.config('prompt.confirm.options');
promptOpts.questions[0].message = 'Bump version from ' + (currentVersion).cyan +
' to ' + semver.inc(currentVersion, patchLevel).yellow + '?';
grunt.config('prompt.confirm.options', promptOpts);
grunt.task.run([
'prompt:confirm',
'checkBranch',
'release',
'bump:' + patchLevel,
'gitcheckout:publish',
'gitpush:publish',
'gitcheckout:revert',
'npm-publish'
]);
});
grunt.registerTask('test-node', ['jshint', 'browserify:filerIssue225', 'connect:serverForNode', 'shell:mocha']);
grunt.registerTask('test-browser', ['jshint', 'build-tests', 'connect:serverForBrowser']);
grunt.registerTask('test', ['clean', 'test-node']);
grunt.registerTask('default', ['test']);
};

Binary file not shown.

Before

Width:  |  Height:  |  Size: 78 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 463 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 216 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 14 KiB

1567
index.html

File diff suppressed because it is too large Load Diff

View File

@ -1 +0,0 @@
console.log('This would be the main JS file.');

28
karma.conf.js Normal file
View File

@ -0,0 +1,28 @@
module.exports = function(config) {
config.set({
singleRun: true,
basePath: '',
files: [
'node_modules/regenerator-runtime/runtime.js',
'tests/dist/index.js'
],
frameworks: ['mocha', 'chai'],
reporters: ['mocha', 'summary'],
client: {
captureConsole: true,
mocha: {
ui: 'bdd',
timeout: 5000,
slow: 250
}
},
summaryReporter: {
// 'failed', 'skipped' or 'all'
show: 'failed',
// Limit the spec label to this length
specLength: 50,
// Show an 'all' column as a summary
overviewColumn: true
}
});
};

View File

@ -1,97 +0,0 @@
// Cherry-picked bits of underscore.js, lodash.js
/**
* Lo-Dash 2.4.0 <http://lodash.com/>
* Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
* Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
* Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
* Available under MIT license <http://lodash.com/license>
*/
var ArrayProto = Array.prototype;
var nativeForEach = ArrayProto.forEach;
var nativeIndexOf = ArrayProto.indexOf;
var nativeSome = ArrayProto.some;
var ObjProto = Object.prototype;
var hasOwnProperty = ObjProto.hasOwnProperty;
var nativeKeys = Object.keys;
var breaker = {};
function has(obj, key) {
return hasOwnProperty.call(obj, key);
}
var keys = nativeKeys || function(obj) {
if (obj !== Object(obj)) throw new TypeError('Invalid object');
var keys = [];
for (var key in obj) if (has(obj, key)) keys.push(key);
return keys;
};
function size(obj) {
if (obj == null) return 0;
return (obj.length === +obj.length) ? obj.length : keys(obj).length;
}
function identity(value) {
return value;
}
function each(obj, iterator, context) {
var i, length;
if (obj == null) return;
if (nativeForEach && obj.forEach === nativeForEach) {
obj.forEach(iterator, context);
} else if (obj.length === +obj.length) {
for (i = 0, length = obj.length; i < length; i++) {
if (iterator.call(context, obj[i], i, obj) === breaker) return;
}
} else {
var keys = keys(obj);
for (i = 0, length = keys.length; i < length; i++) {
if (iterator.call(context, obj[keys[i]], keys[i], obj) === breaker) return;
}
}
};
function any(obj, iterator, context) {
iterator || (iterator = identity);
var result = false;
if (obj == null) return result;
if (nativeSome && obj.some === nativeSome) return obj.some(iterator, context);
each(obj, function(value, index, list) {
if (result || (result = iterator.call(context, value, index, list))) return breaker;
});
return !!result;
};
function contains(obj, target) {
if (obj == null) return false;
if (nativeIndexOf && obj.indexOf === nativeIndexOf) return obj.indexOf(target) != -1;
return any(obj, function(value) {
return value === target;
});
};
function Wrapped(value) {
this.value = value;
}
Wrapped.prototype.has = function(key) {
return has(this.value, key);
};
Wrapped.prototype.contains = function(target) {
return contains(this.value, target);
};
Wrapped.prototype.size = function() {
return size(this.value);
};
function nodash(value) {
// don't wrap if already wrapped, even if wrapped by a different `lodash` constructor
return (value && typeof value == 'object' && !Array.isArray(value) && hasOwnProperty.call(value, '__wrapped__'))
? value
: new Wrapped(value);
}
module.exports = nodash;

13903
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@ -5,48 +5,91 @@
"fs",
"node",
"file",
"system",
"filesystem",
"browser",
"indexeddb",
"idb",
"websql"
"idb"
],
"version": "0.0.35",
"version": "1.4.1",
"author": "Alan K <ack@modeswitch.org> (http://blog.modeswitch.org)",
"homepage": "http://filerjs.github.io/filer",
"bugs": "https://github.com/filerjs/filer/issues",
"license": "BSD",
"license": "BSD-2-Clause",
"scripts": {
"test": "grunt test"
"eslint": "npm run lint",
"eslint:fix": "npm run lint:fix",
"lint": "eslint src tests",
"lint:fix": "eslint --fix src tests",
"test:node": "mocha --timeout 5000 tests",
"pretest:node-debug": "echo \"Open Chrome to chrome://inspect to debug tests...\"",
"test:node-debug": "mocha --timeout 5000 --inspect-brk tests",
"test:manual": "parcel tests/index.html --out-dir tests/dist",
"test:migrations": "mocha tests/filesystems/migrations",
"pretest": "npm run lint",
"test": "npm run karma-mocha",
"posttest": "npm run test:migrations",
"prebuild": "parcel build --global Filer src/index.js --no-minify --out-file filer.js",
"build": "parcel build --global Filer src/index.js --out-file filer.min.js --detailed-report",
"build-tests": "parcel build tests/index.js --no-source-maps --out-dir tests/dist",
"prekarma-mocha-firefox": "npm run build-tests",
"karma-mocha-firefox": "karma start karma.conf.js --browsers FirefoxHeadless",
"prekarma-mocha-chrome": "npm run build-tests",
"karma-mocha-chrome": "karma start karma.conf.js --browsers ChromeHeadless",
"prekarma-mocha": "npm run build-tests",
"karma-mocha": "karma start karma.conf.js --browsers ChromeHeadless,FirefoxHeadless",
"coverage": "nyc mocha tests/index.js",
"release": "run.env release-it"
},
"repository": {
"type": "git",
"url": "https://github.com/filerjs/filer.git"
},
"dependencies": {
"bower": "~1.3.8",
"base64-arraybuffer": "^0.1.2"
"es6-promisify": "^7.0.0",
"minimatch": "^3.0.4",
"schema-utils": "^3.1.1"
},
"devDependencies": {
"chai": "~1.9.1",
"grunt": "~0.4.0",
"grunt-browserify": "^2.1.0",
"grunt-bump": "0.0.13",
"grunt-contrib-clean": "~0.4.0",
"grunt-contrib-compress": "~0.4.1",
"grunt-contrib-concat": "~0.1.3",
"grunt-contrib-connect": "^0.7.1",
"grunt-contrib-jshint": "~0.7.1",
"grunt-contrib-uglify": "~0.1.2",
"grunt-contrib-watch": "~0.3.1",
"grunt-git": "0.2.10",
"grunt-npm": "git://github.com/sedge/grunt-npm.git#branchcheck",
"grunt-prompt": "^1.1.0",
"grunt-shell": "~0.7.0",
"habitat": "^1.1.0",
"mocha": "~1.18.2",
"semver": "^2.3.0",
"requirejs": "^2.1.14"
"regenerator-runtime": "^0.13.9",
"chai": "^4.3.4",
"chai-datetime": "^1.8.0",
"eslint": "^7.32.0",
"fake-indexeddb": "^3.1.7",
"karma": "^6.3.8",
"karma-chai": "^0.1.0",
"karma-chrome-launcher": "^3.1.0",
"karma-firefox-launcher": "^2.1.2",
"karma-mocha": "^2.0.1",
"karma-mocha-reporter": "^2.2.5",
"karma-summary-reporter": "^3.0.0",
"meow": "^10.0.1",
"mocha": "^9.1.3",
"nyc": "^15.1.0",
"parcel-bundler": "^1.12.5",
"pretty-bytes": "^5.6.0",
"release-it": "^14.11.6",
"run.env": "^1.1.0",
"unused-filename": "^3.0.1",
"walk": "^2.3.15"
},
"main": "./src/index.js"
"main": "./src/index.js",
"browser": "./dist/filer.min.js",
"files": [
"src",
"lib",
"dist",
"shims",
"webpack"
],
"nyc": {
"exclude": [
"tests/**/*.js",
"lib/**/*.js",
"src/providers/**/*.js"
],
"reporter": [
"lcov",
"text"
]
}
}

File diff suppressed because one or more lines are too long

View File

@ -1,4 +1,3 @@
var Filer = require('..');
var util = require('../tests/lib/test-utils.js');
function setImmediate(cb) {

65
shims/fs.js Normal file
View File

@ -0,0 +1,65 @@
const { FileSystem } = require('../src/index');
let Provider;
try {
Provider = require('fsProvider');
}
catch (err) {
Provider = require('./providers/default');
}
const provider = new Provider();
let onFsReady;
let onFsError;
let fsReady = new Promise((resolve, reject) => {
onFsReady = resolve;
onFsError = reject;
});
var fsInstance = new FileSystem({ provider }, (err) => {
if (err) {
onFsError(err);
} else {
onFsReady(true);
}
});
function proxyHasProp(target, prop) {
return prop in target;
}
const fsPromises = new Proxy(fsInstance.promises, {
get(target, prop) {
if (!proxyHasProp(target, prop)) {
return;
}
return async (...args) => {
await fsReady;
return await target[prop](...args);
};
},
});
const fs = new Proxy(fsInstance, {
get(target, prop) {
if (!proxyHasProp(target, prop)) {
return;
}
if (prop === 'promises') {
return fsPromises;
}
return (...args) => {
(async () => {
await fsReady;
target[prop](...args);
})();
};
},
});
module.exports = fs;

3
shims/path.js Normal file
View File

@ -0,0 +1,3 @@
const { path } = require('../src/index');
module.exports = path;

View File

@ -0,0 +1,2 @@
const { Default } = require('../../src/providers/index');
module.exports = Default;

View File

@ -0,0 +1,2 @@
const IndexedDB = require('../../src/providers/indexeddb');
module.exports = IndexedDB;

View File

@ -0,0 +1,2 @@
const Memory = require('../../src/providers/memory');
module.exports = Memory;

View File

@ -1,23 +0,0 @@
function FilerBuffer (subject, encoding, nonZero) {
// Automatically turn ArrayBuffer into Uint8Array so that underlying
// Buffer code doesn't just throw away and ignore ArrayBuffer data.
if (subject instanceof ArrayBuffer) {
subject = new Uint8Array(subject);
}
return new Buffer(subject, encoding, nonZero);
};
// Inherit prototype from Buffer
FilerBuffer.prototype = Object.create(Buffer.prototype);
FilerBuffer.prototype.constructor = FilerBuffer;
// Also copy static methods onto FilerBuffer ctor
Object.keys(Buffer).forEach(function (p) {
if (Buffer.hasOwnProperty(p)) {
FilerBuffer[p] = Buffer[p];
}
});
module.exports = FilerBuffer;

View File

@ -15,15 +15,21 @@ module.exports = {
IDB_RO: 'readonly',
IDB_RW: 'readwrite',
WSQL_VERSION: "1",
WSQL_VERSION: '1',
WSQL_SIZE: 5 * 1024 * 1024,
WSQL_DESC: "FileSystem Storage",
WSQL_DESC: 'FileSystem Storage',
MODE_FILE: 'FILE',
MODE_DIRECTORY: 'DIRECTORY',
MODE_SYMBOLIC_LINK: 'SYMLINK',
MODE_META: 'META',
NODE_TYPE_FILE: 'FILE',
NODE_TYPE_DIRECTORY: 'DIRECTORY',
NODE_TYPE_SYMBOLIC_LINK: 'SYMLINK',
NODE_TYPE_META: 'META',
DEFAULT_DIR_PERMISSIONS: 0x1ED, // 755
DEFAULT_FILE_PERMISSIONS: 0x1A4, // 644
FULL_READ_WRITE_EXEC_PERMISSIONS: 0x1FF, // 777
READ_WRITE_PERMISSIONS: 0x1B6, /// 666
SYMLOOP_MAX: 10,
BINARY_MIME_TYPE: 'application/octet-stream',
@ -76,5 +82,49 @@ module.exports = {
ENVIRONMENT: {
TMP: '/tmp',
PATH: ''
},
// Duplicate Node's fs.constants
fsConstants: {
O_RDONLY: 0,
O_WRONLY: 1,
O_RDWR: 2,
S_IFMT: 61440,
S_IFREG: 32768,
S_IFDIR: 16384,
S_IFCHR: 8192,
S_IFBLK: 24576,
S_IFIFO: 4096,
S_IFLNK: 40960,
S_IFSOCK: 49152,
O_CREAT: 512,
O_EXCL: 2048,
O_NOCTTY: 131072,
O_TRUNC: 1024,
O_APPEND: 8,
O_DIRECTORY: 1048576,
O_NOFOLLOW: 256,
O_SYNC: 128,
O_DSYNC: 4194304,
O_SYMLINK: 2097152,
O_NONBLOCK: 4,
S_IRWXU: 448,
S_IRUSR: 256,
S_IWUSR: 128,
S_IXUSR: 64,
S_IRWXG: 56,
S_IRGRP: 32,
S_IWGRP: 16,
S_IXGRP: 8,
S_IRWXO: 7,
S_IROTH: 4,
S_IWOTH: 2,
S_IXOTH: 1,
F_OK: 0,
R_OK: 4,
W_OK: 2,
X_OK: 1,
UV_FS_COPYFILE_EXCL: 1,
COPYFILE_EXCL: 1
}
};

View File

@ -1,6 +1,6 @@
var MODE_FILE = require('./constants.js').MODE_FILE;
var NODE_TYPE_FILE = require('./constants.js').NODE_TYPE_FILE;
module.exports = function DirectoryEntry(id, type) {
this.id = id;
this.type = type || MODE_FILE;
this.type = type || NODE_TYPE_FILE;
};

12
src/dirent.js Normal file
View File

@ -0,0 +1,12 @@
'use strict';
const Stats = require('./stats.js');
function Dirent(path, fileNode, devName) {
this.constructor = Dirent;
Stats.call(this, path, fileNode, devName);
}
Dirent.prototype = Stats.prototype;
module.exports = Dirent;

View File

@ -1,13 +0,0 @@
// Adapt encodings to work with Buffer or Uint8Array, they expect the latter
function decode(buf) {
return buf.toString('utf8');
}
function encode(string) {
return new Buffer(string, 'utf8');
}
module.exports = {
encode: encode,
decode: decode
};

View File

@ -7,7 +7,7 @@ var errors = {};
//'0:OK:success',
//'1:EOF:end of file',
//'2:EADDRINFO:getaddrinfo error',
//'3:EACCES:permission denied',
'3:EACCES:permission denied',
//'4:EAGAIN:resource temporarily unavailable',
//'5:EADDRINUSE:address already in use',
//'6:EADDRNOTAVAIL:address not available',

File diff suppressed because it is too large Load Diff

View File

@ -1,44 +1,111 @@
var _ = require('../../lib/nodash.js');
'use strict';
var isNullPath = require('../path.js').isNull;
var nop = require('../shared.js').nop;
const { promisify } = require('es6-promisify');
var Constants = require('../constants.js');
var FILE_SYSTEM_NAME = Constants.FILE_SYSTEM_NAME;
var FS_FORMAT = Constants.FS_FORMAT;
var FS_READY = Constants.FS_READY;
var FS_PENDING = Constants.FS_PENDING;
var FS_ERROR = Constants.FS_ERROR;
var FS_NODUPEIDCHECK = Constants.FS_NODUPEIDCHECK;
const Path = require('../path.js');
var providers = require('../providers/index.js');
const providers = require('../providers/index.js');
var Shell = require('../shell/shell.js');
var Intercom = require('../../lib/intercom.js');
var FSWatcher = require('../fs-watcher.js');
var Errors = require('../errors.js');
var defaultGuidFn = require('../shared.js').guid;
const Shell = require('../shell/shell.js');
const Intercom = require('../../lib/intercom.js');
const FSWatcher = require('../fs-watcher.js');
const Errors = require('../errors.js');
const {
nop,
guid: defaultGuidFn
} = require('../shared.js');
var STDIN = Constants.STDIN;
var STDOUT = Constants.STDOUT;
var STDERR = Constants.STDERR;
var FIRST_DESCRIPTOR = Constants.FIRST_DESCRIPTOR;
const {
fsConstants,
FILE_SYSTEM_NAME,
FS_FORMAT,
FS_READY,
FS_PENDING,
FS_ERROR,
FS_NODUPEIDCHECK,
STDIN,
STDOUT,
STDERR
} = require('../constants.js');
// The core fs operations live on impl
var impl = require('./implementation.js');
const impl = require('./implementation.js');
// node.js supports a calling pattern that leaves off a callback.
function maybeCallback(callback) {
if(typeof callback === "function") {
if (typeof callback === 'function') {
return callback;
}
return function(err) {
if(err) {
return function (err) {
if (err) {
throw err;
}
};
}
// Default callback that logs an error if passed in
function defaultCallback(err) {
if (err) {
/* eslint no-console: 0 */
console.error('Filer error: ', err);
}
}
// Get a path (String) from a file:// URL. Support URL() like objects
// https://github.com/nodejs/node/blob/968e901aff38a343b1de4addebf79fd8fa991c59/lib/internal/url.js#L1381
function toPathIfFileURL(fileURLOrPath) {
if (!(fileURLOrPath &&
fileURLOrPath.protocol &&
fileURLOrPath.pathname)) {
return fileURLOrPath;
}
if (fileURLOrPath.protocol !== 'file:') {
throw new Errors.EINVAL('only file: URLs are supported for paths', fileURLOrPath);
}
const pathname = fileURLOrPath.pathname;
for (let n = 0; n < pathname.length; n++) {
if (pathname[n] === '%') {
const third = pathname.codePointAt(n + 2) | 0x20;
if (pathname[n + 1] === '2' && third === 102) {
throw new Errors.EINVAL('file: URLs must not include encoded / characters', fileURLOrPath);
}
}
}
return decodeURIComponent(pathname);
}
// Allow Buffers for paths. Assumes we want UTF8.
function toPathIfBuffer(bufferOrPath) {
return Buffer.isBuffer(bufferOrPath) ? bufferOrPath.toString() : bufferOrPath;
}
function validatePath(path, allowRelative) {
if (!path) {
return new Errors.EINVAL('Path must be a string', path);
} else if (Path.isNull(path)) {
return new Errors.EINVAL('Path must be a string without null bytes.', path);
} else if (!allowRelative && !Path.isAbsolute(path)) {
return new Errors.EINVAL('Path must be absolute.', path);
}
}
function processPathArg(args, idx, allowRelative) {
let path = args[idx];
path = toPathIfFileURL(path);
path = toPathIfBuffer(path);
// Some methods specifically allow for rel paths (eg symlink with srcPath)
let err = validatePath(path, allowRelative);
if (err) {
throw err;
}
// Overwrite path arg with converted and validated path
args[idx] = path;
}
/**
* FileSystem
*
@ -69,16 +136,16 @@ function maybeCallback(callback) {
*/
function FileSystem(options, callback) {
options = options || {};
callback = callback || nop;
callback = callback || defaultCallback;
var flags = options.flags;
var guid = options.guid ? options.guid : defaultGuidFn;
var provider = options.provider || new providers.Default(options.name || FILE_SYSTEM_NAME);
const flags = options.flags || [];
const guid = options.guid ? options.guid : defaultGuidFn;
const provider = options.provider || new providers.Default(options.name || FILE_SYSTEM_NAME);
// If we're given a provider, match its name unless we get an explicit name
var name = options.name || provider.name;
var forceFormatting = _(flags).contains(FS_FORMAT);
const name = options.name || provider.name;
const forceFormatting = flags.includes(FS_FORMAT);
var fs = this;
const fs = this;
fs.readyState = FS_PENDING;
fs.name = name;
fs.error = null;
@ -87,30 +154,25 @@ function FileSystem(options, callback) {
fs.stdout = STDOUT;
fs.stderr = STDERR;
// Safely expose the list of open files and file
// descriptor management functions
var openFiles = {};
var nextDescriptor = FIRST_DESCRIPTOR;
Object.defineProperty(this, "openFiles", {
get: function() { return openFiles; }
});
this.allocDescriptor = function(openFileDescription) {
var fd = nextDescriptor ++;
openFiles[fd] = openFileDescription;
return fd;
};
this.releaseDescriptor = function(fd) {
delete openFiles[fd];
};
// Expose Node's fs.constants to users
fs.constants = fsConstants;
// Node also forwards the access mode flags onto fs
fs.F_OK = fsConstants.F_OK;
fs.R_OK = fsConstants.R_OK;
fs.W_OK = fsConstants.W_OK;
fs.X_OK = fsConstants.X_OK;
// Expose Shell constructor
this.Shell = Shell.bind(undefined, this);
// Safely expose the operation queue
var queue = [];
this.queueOrRun = function(operation) {
var error;
let queue = [];
this.queueOrRun = function (operation) {
let error;
if(FS_READY == fs.readyState) {
if (FS_READY === fs.readyState) {
operation.call(fs);
} else if(FS_ERROR == fs.readyState) {
} else if (FS_ERROR === fs.readyState) {
error = new Errors.EFILESYSTEMERROR('unknown error');
} else {
queue.push(operation);
@ -119,25 +181,25 @@ function FileSystem(options, callback) {
return error;
};
function runQueued() {
queue.forEach(function(operation) {
queue.forEach(function (operation) {
operation.call(this);
}.bind(fs));
queue = null;
}
// We support the optional `options` arg from node, but ignore it
this.watch = function(filename, options, listener) {
if(isNullPath(filename)) {
this.watch = function (filename, options, listener) {
if (Path.isNull(filename)) {
throw new Error('Path must be a string without null bytes.');
}
if(typeof options === 'function') {
if (typeof options === 'function') {
listener = options;
options = {};
}
options = options || {};
listener = listener || nop;
var watcher = new FSWatcher();
const watcher = new FSWatcher();
watcher.start(filename, false, options.recursive);
watcher.on('change', listener);
@ -146,24 +208,24 @@ function FileSystem(options, callback) {
// Deal with various approaches to node ID creation
function wrappedGuidFn(context) {
return function(callback) {
return function (callback) {
// Skip the duplicate ID check if asked to
if(_(flags).contains(FS_NODUPEIDCHECK)) {
if (flags.includes(FS_NODUPEIDCHECK)) {
callback(null, guid());
return;
}
// Otherwise (default) make sure this id is unused first
function guidWithCheck(callback) {
var id = guid();
context.getObject(id, function(err, value) {
if(err) {
const id = guid();
context.getObject(id, function (err, value) {
if (err) {
callback(err);
return;
}
// If this id is unused, use it, otherwise find another
if(!value) {
if (!value) {
callback(null, id);
} else {
guidWithCheck(callback);
@ -177,27 +239,28 @@ function FileSystem(options, callback) {
// Let other instances (in this or other windows) know about
// any changes to this fs instance.
function broadcastChanges(changes) {
if(!changes.length) {
if (!changes.length) {
return;
}
var intercom = Intercom.getInstance();
changes.forEach(function(change) {
const intercom = Intercom.getInstance();
changes.forEach(function (change) {
intercom.emit(change.event, change.path);
});
}
// Open file system storage provider
provider.open(function(err) {
provider.open(function (err) {
function complete(error) {
function wrappedContext(methodName) {
var context = provider[methodName]();
let context = provider[methodName]();
context.name = name;
context.flags = flags;
context.changes = [];
context.guid = wrappedGuidFn(context);
// When the context is finished, let the fs deal with any change events
context.close = function() {
var changes = context.changes;
context.close = function () {
let changes = context.changes;
broadcastChanges(changes);
changes.length = 0;
};
@ -210,15 +273,15 @@ function FileSystem(options, callback) {
// for paths updated during the lifetime of the context). From this
// point forward we won't call open again, so it's safe to drop it.
fs.provider = {
openReadWriteContext: function() {
openReadWriteContext: function () {
return wrappedContext('getReadWriteContext');
},
openReadOnlyContext: function() {
openReadOnlyContext: function () {
return wrappedContext('getReadOnlyContext');
}
};
if(error) {
if (error) {
fs.readyState = FS_ERROR;
} else {
fs.readyState = FS_READY;
@ -227,18 +290,18 @@ function FileSystem(options, callback) {
callback(error, fs);
}
if(err) {
if (err) {
return complete(err);
}
var context = provider.getReadWriteContext();
const context = provider.getReadWriteContext();
context.guid = wrappedGuidFn(context);
// Mount the filesystem, formatting if necessary
if(forceFormatting) {
if (forceFormatting) {
// Wipe the storage provider, then write root block
context.clear(function(err) {
if(err) {
context.clear(function (err) {
if (err) {
return complete(err);
}
impl.ensureRootDirectory(context, complete);
@ -248,94 +311,128 @@ function FileSystem(options, callback) {
impl.ensureRootDirectory(context, complete);
}
});
FileSystem.prototype.promises = {};
/**
* Public API for FileSystem. All node.js methods that are exposed on fs.promises
* include `promise: true`. We also include our own extra methods, but skip the
* fd versions to match node.js, which puts these on a `FileHandle` object.
* Any method that deals with path argument(s) also includes the position of
* those args in one of `absPathArgs: [...]` or `relPathArgs: [...]`, so they
* can be processed and validated before being passed on to the method.
*/
[
{ name: 'appendFile', promises: true, absPathArgs: [0] },
{ name: 'access', promises: true, absPathArgs: [0] },
{ name: 'chown', promises: true, absPathArgs: [0] },
{ name: 'chmod', promises: true, absPathArgs: [0] },
{ name: 'close' },
// copyFile - https://github.com/filerjs/filer/issues/436
{ name: 'exists', absPathArgs: [0] },
{ name: 'fchown' },
{ name: 'fchmod' },
// fdatasync - https://github.com/filerjs/filer/issues/653
{ name: 'fgetxattr' },
{ name: 'fremovexattr' },
{ name: 'fsetxattr' },
{ name: 'fstat' },
{ name: 'fsync' },
{ name: 'ftruncate' },
{ name: 'futimes' },
{ name: 'getxattr', promises: true, absPathArgs: [0] },
// lchown - https://github.com/filerjs/filer/issues/620
// lchmod - https://github.com/filerjs/filer/issues/619
{ name: 'link', promises: true, absPathArgs: [0, 1] },
{ name: 'lseek' },
{ name: 'lstat', promises: true },
{ name: 'mkdir', promises: true, absPathArgs: [0] },
{ name: 'mkdtemp', promises: true },
{ name: 'mknod', promises: true, absPathArgs: [0] },
{ name: 'open', promises: true, absPathArgs: [0] },
{ name: 'readdir', promises: true, absPathArgs: [0] },
{ name: 'read' },
{ name: 'readFile', promises: true, absPathArgs: [0] },
{ name: 'readlink', promises: true, absPathArgs: [0] },
// realpath - https://github.com/filerjs/filer/issues/85
{ name: 'removexattr', promises: true, absPathArgs: [0] },
{ name: 'rename', promises: true, absPathArgs: [0, 1] },
{ name: 'rmdir', promises: true, absPathArgs: [0] },
{ name: 'setxattr', promises: true, absPathArgs: [0] },
{ name: 'stat', promises: true, absPathArgs: [0] },
{ name: 'symlink', promises: true, relPathArgs: [0], absPathArgs: [1] },
{ name: 'truncate', promises: true, absPathArgs: [0] },
// unwatchFile - https://github.com/filerjs/filer/pull/553
{ name: 'unlink', promises: true, absPathArgs: [0] },
{ name: 'utimes', promises: true, absPathArgs: [0] },
// watch - implemented above in `this.watch`
// watchFile - https://github.com/filerjs/filer/issues/654
{ name: 'writeFile', promises: true, absPathArgs: [0] },
{ name: 'write' }
].forEach(function (method) {
const methodName = method.name;
const shouldPromisify = method.promises === true;
FileSystem.prototype[methodName] = function () {
const fs = this;
const args = Array.prototype.slice.call(arguments, 0);
const lastArgIndex = args.length - 1;
// We may or may not get a callback, and since node.js supports
// fire-and-forget style fs operations, we have to dance a bit here.
const missingCallback = typeof args[lastArgIndex] !== 'function';
const callback = maybeCallback(args[lastArgIndex]);
// Deal with path arguments, validating and normalizing Buffer and file:// URLs
if (method.absPathArgs) {
method.absPathArgs.forEach(pathArg => processPathArg(args, pathArg, false));
}
if (method.relPathArgs) {
method.relPathArgs.forEach(pathArg => processPathArg(args, pathArg, true));
}
const error = fs.queueOrRun(function () {
const context = fs.provider.openReadWriteContext();
// Fail early if the filesystem is in an error state (e.g.,
// provider failed to open.
if (FS_ERROR === fs.readyState) {
const err = new Errors.EFILESYSTEMERROR('filesystem unavailable, operation canceled');
return callback.call(fs, err);
}
// Wrap the callback so we can explicitly close the context
function complete() {
context.close();
callback.apply(fs, arguments);
}
// Either add or replace the callback with our wrapper complete()
if (missingCallback) {
args.push(complete);
} else {
args[lastArgIndex] = complete;
}
// Forward this call to the impl's version, using the following
// call signature, with complete() as the callback/last-arg now:
// fn(fs, context, arg0, arg1, ... , complete);
const fnArgs = [context].concat(args);
impl[methodName].apply(null, fnArgs);
});
if (error) {
callback(error);
}
};
// Add to fs.promises if appropriate
if (shouldPromisify) {
FileSystem.prototype.promises[methodName] = promisify(FileSystem.prototype[methodName].bind(fs));
}
});
}
// Expose storage providers on FileSystem constructor
FileSystem.providers = providers;
/**
* Public API for FileSystem
*/
[
'open',
'close',
'mknod',
'mkdir',
'rmdir',
'stat',
'fstat',
'link',
'unlink',
'read',
'readFile',
'write',
'writeFile',
'appendFile',
'exists',
'lseek',
'readdir',
'rename',
'readlink',
'symlink',
'lstat',
'truncate',
'ftruncate',
'utimes',
'futimes',
'setxattr',
'getxattr',
'fsetxattr',
'fgetxattr',
'removexattr',
'fremovexattr'
].forEach(function(methodName) {
FileSystem.prototype[methodName] = function() {
var fs = this;
var args = Array.prototype.slice.call(arguments, 0);
var lastArgIndex = args.length - 1;
// We may or may not get a callback, and since node.js supports
// fire-and-forget style fs operations, we have to dance a bit here.
var missingCallback = typeof args[lastArgIndex] !== 'function';
var callback = maybeCallback(args[lastArgIndex]);
var error = fs.queueOrRun(function() {
var context = fs.provider.openReadWriteContext();
// Fail early if the filesystem is in an error state (e.g.,
// provider failed to open.
if(FS_ERROR === fs.readyState) {
var err = new Errors.EFILESYSTEMERROR('filesystem unavailable, operation canceled');
return callback.call(fs, err);
}
// Wrap the callback so we can explicitly close the context
function complete() {
context.close();
callback.apply(fs, arguments);
}
// Either add or replace the callback with our wrapper complete()
if(missingCallback) {
args.push(complete);
} else {
args[lastArgIndex] = complete;
}
// Forward this call to the impl's version, using the following
// call signature, with complete() as the callback/last-arg now:
// fn(fs, context, arg0, arg1, ... , complete);
var fnArgs = [fs, context].concat(args);
impl[methodName].apply(null, fnArgs);
});
if(error) {
callback(error);
}
};
});
FileSystem.prototype.Shell = function(options) {
return new Shell(this, options);
};
module.exports = FileSystem;

View File

@ -1,6 +1,8 @@
var EventEmitter = require('../lib/eventemitter.js');
var Path = require('./path.js');
var Intercom = require('../lib/intercom.js');
'using strict';
const EventEmitter = require('../lib/eventemitter.js');
const Path = require('./path.js');
const Intercom = require('../lib/intercom.js');
/**
* FSWatcher based on node.js' FSWatcher
@ -8,10 +10,10 @@ var Intercom = require('../lib/intercom.js');
*/
function FSWatcher() {
EventEmitter.call(this);
var self = this;
var recursive = false;
var recursivePathPrefix;
var filename;
const self = this;
let recursive = false;
let recursivePathPrefix;
let filename;
function onchange(path) {
// Watch for exact filename, or parent path when recursive is true.
@ -46,12 +48,12 @@ function FSWatcher() {
recursivePathPrefix = filename === '/' ? '/' : filename + '/';
}
var intercom = Intercom.getInstance();
const intercom = Intercom.getInstance();
intercom.on('change', onchange);
};
self.close = function() {
var intercom = Intercom.getInstance();
const intercom = Intercom.getInstance();
intercom.off('change', onchange);
self.removeAllListeners('change');
};

View File

@ -1,6 +1,34 @@
module.exports = {
let fs = null;
let Filer = null;
module.exports = Filer = {
FileSystem: require('./filesystem/interface.js'),
Buffer: require('./buffer.js'),
Buffer: Buffer,
// We previously called this Path, but node calls it path. Do both
Path: require('./path.js'),
Errors: require('./errors.js')
path: require('./path.js'),
Errors: require('./errors.js'),
Shell: require('./shell/shell.js'),
/**
* @deprecated Importing filer from your webpack config is not recommended.
*
* The filer `FilerWebpackPlugin` class is exposed directly.
*
* ```
* const { FilerWebpackPlugin } = require('filer/webpack');
* ```
*/
FilerWebpackPlugin: require('./webpack-plugin'),
};
// Add a getter for the `fs` instance, which returns
// a Filer FileSystem instance, using the default provider/flags.
Object.defineProperty(Filer, 'fs', {
enumerable: true,
get() {
if(!fs) {
fs = new Filer.FileSystem();
}
return fs;
}
});

View File

@ -1,53 +1,135 @@
var MODE_FILE = require('./constants.js').MODE_FILE;
const {
NODE_TYPE_FILE,
NODE_TYPE_DIRECTORY,
NODE_TYPE_SYMBOLIC_LINK,
DEFAULT_FILE_PERMISSIONS,
DEFAULT_DIR_PERMISSIONS
} = require('./constants');
const {
S_IFREG,
S_IFDIR,
S_IFLNK
} = require('./constants').fsConstants;
function Node(options) {
var now = Date.now();
this.id = options.id;
this.mode = options.mode || MODE_FILE; // node type (file, directory, etc)
this.size = options.size || 0; // size (bytes for files, entries for directories)
this.atime = options.atime || now; // access time (will mirror ctime after creation)
this.ctime = options.ctime || now; // creation/change time
this.mtime = options.mtime || now; // modified time
this.flags = options.flags || []; // file flags
this.xattrs = options.xattrs || {}; // extended attributes
this.nlinks = options.nlinks || 0; // links count
this.version = options.version || 0; // node version
this.blksize = undefined; // block size
this.nblocks = 1; // blocks count
this.data = options.data; // id for data object
}
// Make sure the options object has an id on property,
// either from caller or one we generate using supplied guid fn.
/**
* Make sure the options object has an id on property,
* either from caller or one we generate using supplied guid fn.
*/
function ensureID(options, prop, callback) {
if(options[prop]) {
callback(null);
} else {
options.guid(function(err, id) {
options[prop] = id;
callback(err);
});
return callback();
}
options.guid(function(err, id) {
if(err) {
return callback(err);
}
options[prop] = id;
callback();
});
}
/**
* Generate a POSIX mode (integer) for the node type and permissions.
* Use default permissions if we aren't passed any.
*/
function generateMode(nodeType, modePermissions) {
switch(nodeType) {
case NODE_TYPE_DIRECTORY:
return (modePermissions || DEFAULT_DIR_PERMISSIONS) | S_IFDIR;
case NODE_TYPE_SYMBOLIC_LINK:
return (modePermissions || DEFAULT_FILE_PERMISSIONS) | S_IFLNK;
case NODE_TYPE_FILE:
// falls through
default:
return (modePermissions || DEFAULT_FILE_PERMISSIONS) | S_IFREG;
}
}
Node.create = function(options, callback) {
/**
* Common properties for the layout of a Node
*/
class Node {
constructor(options) {
var now = Date.now();
this.id = options.id;
this.data = options.data; // id for data object
this.size = options.size || 0; // size (bytes for files, entries for directories)
this.atime = options.atime || now; // access time (will mirror ctime after creation)
this.ctime = options.ctime || now; // creation/change time
this.mtime = options.mtime || now; // modified time
this.flags = options.flags || []; // file flags
this.xattrs = options.xattrs || {}; // extended attributes
this.nlinks = options.nlinks || 0; // links count
// Historically, Filer's node layout has referred to the
// node type as `mode`, and done so using a String. In
// a POSIX filesystem, the mode is a number that combines
// both node type and permission bits. Internal we use `type`,
// but store it in the database as `mode` for backward
// compatibility.
if(typeof options.type === 'string') {
this.type = options.type;
} else if(typeof options.mode === 'string') {
this.type = options.mode;
} else {
this.type = NODE_TYPE_FILE;
}
// Extra mode permissions and ownership info
this.permissions = options.permissions || generateMode(this.type);
this.uid = options.uid || 0x0; // owner name
this.gid = options.gid || 0x0; // group name
}
/**
* Serialize a Node to JSON. Everything is as expected except
* that we use `mode` for `type` to maintain backward compatibility.
*/
toJSON() {
return {
id: this.id,
data: this.data,
size: this.size,
atime: this.atime,
ctime: this.ctime,
mtime: this.ctime,
flags: this.flags,
xattrs: this.xattrs,
nlinks: this.nlinks,
// Use `mode` for `type` to keep backward compatibility
mode: this.type,
permissions: this.permissions,
uid: this.uid,
gid: this.gid
};
}
// Return complete POSIX `mode` for node type + permissions. See:
// http://man7.org/linux/man-pages/man2/chmod.2.html
get mode() {
return generateMode(this.type, this.permissions);
}
// When setting the `mode` we assume permissions bits only (not changing type)
set mode(value) {
this.permissions = value;
}
}
module.exports.create = function create(options, callback) {
// We expect both options.id and options.data to be provided/generated.
ensureID(options, 'id', function(err) {
if(err) {
callback(err);
return;
return callback(err);
}
ensureID(options, 'data', function(err) {
if(err) {
callback(err);
return;
return callback(err);
}
callback(null, new Node(options));
});
});
};
module.exports = Node;

View File

@ -1,4 +1,5 @@
var Errors = require('./errors.js');
const Errors = require('./errors.js');
const Node = require('./node');
function OpenFileDescription(path, id, flags, position) {
this.path = path;
@ -22,7 +23,7 @@ OpenFileDescription.prototype.getNode = function(context, callback) {
return callback(new Errors.EBADF('file descriptor refers to unknown node', path));
}
callback(null, node);
Node.create(node, callback);
}
context.getObject(id, check_if_node_exists);

44
src/open-files.js Normal file
View File

@ -0,0 +1,44 @@
const { FIRST_DESCRIPTOR } = require('./constants');
const openFiles = {};
/**
* Start at FIRST_DESCRIPTOR and go until we find
* an empty file descriptor, then return it.
*/
const getEmptyDescriptor = () => {
let fd = FIRST_DESCRIPTOR;
while(getOpenFileDescription(fd)) {
fd++;
}
return fd;
};
/**
* Look up the open file description object for a given
* file descriptor.
*/
const getOpenFileDescription = ofd => openFiles[ofd];
/**
* Allocate a new file descriptor for the given
* open file description.
*/
const allocDescriptor = openFileDescription => {
const ofd = getEmptyDescriptor();
openFiles[ofd] = openFileDescription;
return ofd;
};
/**
* Release the given existing file descriptor created
* with allocDescriptor().
*/
const releaseDescriptor = ofd => delete openFiles[ofd];
module.exports = {
allocDescriptor,
releaseDescriptor,
getOpenFileDescription
};

View File

@ -1,224 +1,49 @@
// Copyright Joyent, Inc. and other Node contributors.
//
// 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.
/**
* Patch process to add process.cwd(), always giving the root dir.
* NOTE: this line needs to happen *before* we require in `path`.
*/
process.cwd = () => '/';
// Based on https://github.com/joyent/node/blob/41e53e557992a7d552a8e23de035f9463da25c99/lib/path.js
/**
* https://github.com/browserify/path-browserify via Parcel.
* We use is as a base for our own Filer.Path, and patch/add
* a few things we need for the browser environment.
*/
const nodePath = require('path');
const filerPath = Object.assign({}, nodePath);
// resolves . and .. elements in a path array with directory names there
// must be no slashes, empty elements, or device names (c:\) in the array
// (so also no leading and trailing slashes - it does not distinguish
// relative and absolute paths)
function normalizeArray(parts, allowAboveRoot) {
// if the path tries to go above the root, `up` ends up > 0
var up = 0;
for (var i = parts.length - 1; i >= 0; i--) {
var last = parts[i];
if (last === '.') {
parts.splice(i, 1);
} else if (last === '..') {
parts.splice(i, 1);
up++;
} else if (up) {
parts.splice(i, 1);
up--;
}
}
// if the path is allowed to go above the root, restore leading ..s
if (allowAboveRoot) {
for (; up--; up) {
parts.unshift('..');
}
}
return parts;
}
// Split a filename into [root, dir, basename, ext], unix version
// 'root' is just a slash, or nothing.
var splitPathRe =
/^(\/?)([\s\S]+\/(?!$)|\/)?((?:\.{1,2}$|[\s\S]+?)?(\.[^.\/]*)?)$/;
var splitPath = function(filename) {
var result = splitPathRe.exec(filename);
return [result[1] || '', result[2] || '', result[3] || '', result[4] || ''];
/**
* Patch path.basename() to return / vs. ''
*/
filerPath.basename = (path, ext) => {
const basename = nodePath.basename(path, ext);
return basename === '' ? '/' : basename;
};
// path.resolve([from ...], to)
function resolve() {
var resolvedPath = '',
resolvedAbsolute = false;
for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
// XXXidbfs: we don't have process.cwd() so we use '/' as a fallback
var path = (i >= 0) ? arguments[i] : '/';
// Skip empty and invalid entries
if (typeof path !== 'string' || !path) {
continue;
}
resolvedPath = path + '/' + resolvedPath;
resolvedAbsolute = path.charAt(0) === '/';
}
// At this point the path should be resolved to a full absolute path, but
// handle relative paths to be safe (might happen when process.cwd() fails)
// Normalize the path
resolvedPath = normalizeArray(resolvedPath.split('/').filter(function(p) {
return !!p;
}), !resolvedAbsolute).join('/');
return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.';
}
// path.normalize(path)
function normalize(path) {
var isAbsolute = path.charAt(0) === '/',
trailingSlash = path.substr(-1) === '/';
// Normalize the path
path = normalizeArray(path.split('/').filter(function(p) {
return !!p;
}), !isAbsolute).join('/');
if (!path && !isAbsolute) {
path = '.';
}
/*
if (path && trailingSlash) {
path += '/';
}
*/
return (isAbsolute ? '/' : '') + path;
}
function join() {
var paths = Array.prototype.slice.call(arguments, 0);
return normalize(paths.filter(function(p, index) {
return p && typeof p === 'string';
}).join('/'));
}
// path.relative(from, to)
function relative(from, to) {
from = exports.resolve(from).substr(1);
to = exports.resolve(to).substr(1);
function trim(arr) {
var start = 0;
for (; start < arr.length; start++) {
if (arr[start] !== '') break;
}
var end = arr.length - 1;
for (; end >= 0; end--) {
if (arr[end] !== '') break;
}
if (start > end) return [];
return arr.slice(start, end - start + 1);
}
var fromParts = trim(from.split('/'));
var toParts = trim(to.split('/'));
var length = Math.min(fromParts.length, toParts.length);
var samePartsLength = length;
for (var i = 0; i < length; i++) {
if (fromParts[i] !== toParts[i]) {
samePartsLength = i;
break;
}
}
var outputParts = [];
for (var i = samePartsLength; i < fromParts.length; i++) {
outputParts.push('..');
}
outputParts = outputParts.concat(toParts.slice(samePartsLength));
return outputParts.join('/');
}
function dirname(path) {
var result = splitPath(path),
root = result[0],
dir = result[1];
if (!root && !dir) {
// No dirname whatsoever
return '.';
}
if (dir) {
// It has a dirname, strip trailing slash
dir = dir.substr(0, dir.length - 1);
}
return root + dir;
}
function basename(path, ext) {
var f = splitPath(path)[2];
// TODO: make this comparison case-insensitive on windows?
if (ext && f.substr(-1 * ext.length) === ext) {
f = f.substr(0, f.length - ext.length);
}
// XXXidbfs: node.js just does `return f`
return f === "" ? "/" : f;
}
function extname(path) {
return splitPath(path)[3];
}
function isAbsolute(path) {
if(path.charAt(0) === '/') {
return true;
}
return false;
}
function isNull(path) {
if (('' + path).indexOf('\u0000') !== -1) {
return true;
}
return false;
}
// XXXidbfs: we don't support path.exists() or path.existsSync(), which
// are deprecated, and need a FileSystem instance to work. Use fs.stat().
module.exports = {
normalize: normalize,
resolve: resolve,
join: join,
relative: relative,
sep: '/',
delimiter: ':',
dirname: dirname,
basename: basename,
extname: extname,
isAbsolute: isAbsolute,
isNull: isNull
/**
* Patch path.normalize() to not add a trailing /
*/
filerPath.normalize = (path) => {
path = nodePath.normalize(path);
return path === '/' ? path : filerPath.removeTrailing(path);
};
/**
* Add new utility method isNull() to path: check for null paths.
*/
filerPath.isNull = path => ('' + path).indexOf('\u0000') !== -1;
/**
* Add new utility method addTrailing() to add trailing / without doubling to //.
*/
filerPath.addTrailing = path => path.replace(/\/*$/, '/');
/**
* Add new utility method removeTrailing() to remove trailing /, dealing with multiple
*/
filerPath.removeTrailing = path => {
path = path.replace(/\/*$/, '');
return path === '' ? '/' : path;
};
module.exports = filerPath;

View File

@ -1,35 +1,8 @@
var IndexedDB = require('./indexeddb.js');
var WebSQL = require('./websql.js');
var Memory = require('./memory.js');
const IndexedDB = require('./indexeddb.js');
const Memory = require('./memory.js');
module.exports = {
IndexedDB: IndexedDB,
WebSQL: WebSQL,
Memory: Memory,
/**
* Convenience Provider references
*/
// The default provider to use when none is specified
Default: IndexedDB,
// The Fallback provider does automatic fallback checks
Fallback: (function() {
if(IndexedDB.isSupported()) {
return IndexedDB;
}
if(WebSQL.isSupported()) {
return WebSQL;
}
function NotSupported() {
throw "[Filer Error] Your browser doesn't support IndexedDB or WebSQL.";
}
NotSupported.isSupported = function() {
return false;
};
return NotSupported;
}())
Memory: Memory
};

View File

@ -2,98 +2,104 @@ var FILE_SYSTEM_NAME = require('../constants.js').FILE_SYSTEM_NAME;
var FILE_STORE_NAME = require('../constants.js').FILE_STORE_NAME;
var IDB_RW = require('../constants.js').IDB_RW;
var IDB_RO = require('../constants.js').IDB_RO;
var Errors = require('../errors.js');
var FilerBuffer = require('../buffer.js');
var indexedDB = global.indexedDB ||
global.mozIndexedDB ||
global.webkitIndexedDB ||
global.msIndexedDB;
function IndexedDBContext(db, mode) {
var transaction = db.transaction(FILE_STORE_NAME, mode);
this.objectStore = transaction.objectStore(FILE_STORE_NAME);
this.db = db;
this.mode = mode;
}
IndexedDBContext.prototype._getObjectStore = function() {
if(this.objectStore) {
return this.objectStore;
}
var transaction = this.db.transaction(FILE_STORE_NAME, this.mode);
this.objectStore = transaction.objectStore(FILE_STORE_NAME);
return this.objectStore;
};
IndexedDBContext.prototype.clear = function(callback) {
try {
var request = this.objectStore.clear();
request.onsuccess = function(event) {
var objectStore = this._getObjectStore();
var request = objectStore.clear();
request.onsuccess = function() {
callback();
};
request.onerror = function(error) {
callback(error);
request.onerror = function(event) {
event.preventDefault();
callback(event.error);
};
} catch(e) {
callback(e);
} catch(err) {
callback(err);
}
};
function _get(objectStore, key, callback) {
IndexedDBContext.prototype._get = function(key, callback) {
try {
var objectStore = this._getObjectStore();
var request = objectStore.get(key);
request.onsuccess = function onsuccess(event) {
var result = event.target.result;
callback(null, result);
};
request.onerror = function onerror(error) {
callback(error);
request.onerror = function(event) {
event.preventDefault();
callback(event.error);
};
} catch(e) {
callback(e);
} catch(err) {
callback(err);
}
}
};
IndexedDBContext.prototype.getObject = function(key, callback) {
_get(this.objectStore, key, callback);
this._get(key, callback);
};
IndexedDBContext.prototype.getBuffer = function(key, callback) {
_get(this.objectStore, key, function(err, arrayBuffer) {
this._get(key, function(err, arrayBuffer) {
if(err) {
return callback(err);
}
callback(null, new FilerBuffer(arrayBuffer));
callback(null, Buffer.from(arrayBuffer));
});
};
function _put(objectStore, key, value, callback) {
IndexedDBContext.prototype._put = function(key, value, callback) {
try {
var objectStore = this._getObjectStore();
var request = objectStore.put(value, key);
request.onsuccess = function onsuccess(event) {
var result = event.target.result;
callback(null, result);
};
request.onerror = function onerror(error) {
callback(error);
request.onerror = function(event) {
event.preventDefault();
callback(event.error);
};
} catch(e) {
callback(e);
} catch(err) {
callback(err);
}
}
};
IndexedDBContext.prototype.putObject = function(key, value, callback) {
_put(this.objectStore, key, value, callback);
this._put(key, value, callback);
};
IndexedDBContext.prototype.putBuffer = function(key, uint8BackedBuffer, callback) {
var buf;
if(!Buffer._useTypedArrays) { // workaround for fxos 1.3
buf = uint8BackedBuffer.toArrayBuffer();
} else {
buf = uint8BackedBuffer.buffer;
}
_put(this.objectStore, key, buf, callback);
var buf = uint8BackedBuffer.buffer;
this._put(key, buf, callback);
};
IndexedDBContext.prototype.delete = function(key, callback) {
try {
var request = this.objectStore.delete(key);
var objectStore = this._getObjectStore();
var request = objectStore.delete(key);
request.onsuccess = function onsuccess(event) {
var result = event.target.result;
callback(null, result);
};
request.onerror = function(error) {
callback(error);
request.onerror = function(event) {
event.preventDefault();
callback(event.error);
};
} catch(e) {
callback(e);
} catch(err) {
callback(err);
}
};
@ -103,6 +109,10 @@ function IndexedDB(name) {
this.db = null;
}
IndexedDB.isSupported = function() {
var indexedDB = global.indexedDB ||
global.mozIndexedDB ||
global.webkitIndexedDB ||
global.msIndexedDB;
return !!indexedDB;
};
@ -114,32 +124,40 @@ IndexedDB.prototype.open = function(callback) {
return callback();
}
// NOTE: we're not using versioned databases.
var openRequest = indexedDB.open(that.name);
try {
var indexedDB = global.indexedDB ||
global.mozIndexedDB ||
global.webkitIndexedDB ||
global.msIndexedDB;
// If the db doesn't exist, we'll create it
openRequest.onupgradeneeded = function onupgradeneeded(event) {
var db = event.target.result;
// NOTE: we're not using versioned databases.
var openRequest = indexedDB.open(that.name);
if(db.objectStoreNames.contains(FILE_STORE_NAME)) {
db.deleteObjectStore(FILE_STORE_NAME);
}
db.createObjectStore(FILE_STORE_NAME);
};
// If the db doesn't exist, we'll create it
openRequest.onupgradeneeded = function onupgradeneeded(event) {
var db = event.target.result;
openRequest.onsuccess = function onsuccess(event) {
that.db = event.target.result;
callback();
};
openRequest.onerror = function onerror(error) {
callback(new Errors.EINVAL('IndexedDB cannot be accessed. If private browsing is enabled, disable it.'));
};
if(db.objectStoreNames.contains(FILE_STORE_NAME)) {
db.deleteObjectStore(FILE_STORE_NAME);
}
db.createObjectStore(FILE_STORE_NAME);
};
openRequest.onsuccess = function onsuccess(event) {
that.db = event.target.result;
callback();
};
openRequest.onerror = function onerror(event) {
event.preventDefault();
callback(event.error);
};
} catch(err) {
callback(err);
}
};
IndexedDB.prototype.getReadOnlyContext = function() {
// Due to timing issues in Chrome with readwrite vs. readonly indexeddb transactions
// always use readwrite so we can make sure pending commits finish before callbacks.
// See https://github.com/js-platform/filer/issues/128
return new IndexedDBContext(this.db, IDB_RW);
return new IndexedDBContext(this.db, IDB_RO);
};
IndexedDB.prototype.getReadWriteContext = function() {
return new IndexedDBContext(this.db, IDB_RW);

View File

@ -9,7 +9,7 @@ var asyncCallback = require('../../lib/async.js').setImmediate;
var createDB = (function() {
var pool = {};
return function getOrCreate(name) {
if(!pool.hasOwnProperty(name)) {
if(!Object.prototype.hasOwnProperty.call(pool, name)) {
pool[name] = {};
}
return pool[name];
@ -24,7 +24,7 @@ function MemoryContext(db, readOnly) {
MemoryContext.prototype.clear = function(callback) {
if(this.readOnly) {
asyncCallback(function() {
callback("[MemoryContext] Error: write operation on read only context");
callback('[MemoryContext] Error: write operation on read only context');
});
return;
}
@ -49,7 +49,7 @@ MemoryContext.prototype.putBuffer =
function(key, value, callback) {
if(this.readOnly) {
asyncCallback(function() {
callback("[MemoryContext] Error: write operation on read only context");
callback('[MemoryContext] Error: write operation on read only context');
});
return;
}
@ -60,7 +60,7 @@ function(key, value, callback) {
MemoryContext.prototype.delete = function(key, callback) {
if(this.readOnly) {
asyncCallback(function() {
callback("[MemoryContext] Error: write operation on read only context");
callback('[MemoryContext] Error: write operation on read only context');
});
return;
}

View File

@ -1,171 +0,0 @@
var FILE_SYSTEM_NAME = require('../constants.js').FILE_SYSTEM_NAME;
var FILE_STORE_NAME = require('../constants.js').FILE_STORE_NAME;
var WSQL_VERSION = require('../constants.js').WSQL_VERSION;
var WSQL_SIZE = require('../constants.js').WSQL_SIZE;
var WSQL_DESC = require('../constants.js').WSQL_DESC;
var Errors = require('../errors.js');
var FilerBuffer = require('../buffer.js');
var base64ArrayBuffer = require('base64-arraybuffer');
function WebSQLContext(db, isReadOnly) {
var that = this;
this.getTransaction = function(callback) {
if(that.transaction) {
callback(that.transaction);
return;
}
// Either do readTransaction() (read-only) or transaction() (read/write)
db[isReadOnly ? 'readTransaction' : 'transaction'](function(transaction) {
that.transaction = transaction;
callback(transaction);
});
};
}
WebSQLContext.prototype.clear = function(callback) {
function onError(transaction, error) {
callback(error);
}
function onSuccess(transaction, result) {
callback(null);
}
this.getTransaction(function(transaction) {
transaction.executeSql("DELETE FROM " + FILE_STORE_NAME + ";",
[], onSuccess, onError);
});
};
function _get(getTransaction, key, callback) {
function onSuccess(transaction, result) {
// If the key isn't found, return null
var value = result.rows.length === 0 ? null : result.rows.item(0).data;
callback(null, value);
}
function onError(transaction, error) {
callback(error);
}
getTransaction(function(transaction) {
transaction.executeSql("SELECT data FROM " + FILE_STORE_NAME + " WHERE id = ? LIMIT 1;",
[key], onSuccess, onError);
});
}
WebSQLContext.prototype.getObject = function(key, callback) {
_get(this.getTransaction, key, function(err, result) {
if(err) {
return callback(err);
}
try {
if(result) {
result = JSON.parse(result);
}
} catch(e) {
return callback(e);
}
callback(null, result);
});
};
WebSQLContext.prototype.getBuffer = function(key, callback) {
_get(this.getTransaction, key, function(err, result) {
if(err) {
return callback(err);
}
// Deal with zero-length ArrayBuffers, which will be encoded as ''
if(result || result === '') {
var arrayBuffer = base64ArrayBuffer.decode(result);
result = new FilerBuffer(arrayBuffer);
}
callback(null, result);
});
};
function _put(getTransaction, key, value, callback) {
function onSuccess(transaction, result) {
callback(null);
}
function onError(transaction, error) {
callback(error);
}
getTransaction(function(transaction) {
transaction.executeSql("INSERT OR REPLACE INTO " + FILE_STORE_NAME + " (id, data) VALUES (?, ?);",
[key, value], onSuccess, onError);
});
}
WebSQLContext.prototype.putObject = function(key, value, callback) {
var json = JSON.stringify(value);
_put(this.getTransaction, key, json, callback);
};
WebSQLContext.prototype.putBuffer = function(key, uint8BackedBuffer, callback) {
var base64 = base64ArrayBuffer.encode(uint8BackedBuffer.buffer);
_put(this.getTransaction, key, base64, callback);
};
WebSQLContext.prototype.delete = function(key, callback) {
function onSuccess(transaction, result) {
callback(null);
}
function onError(transaction, error) {
callback(error);
}
this.getTransaction(function(transaction) {
transaction.executeSql("DELETE FROM " + FILE_STORE_NAME + " WHERE id = ?;",
[key], onSuccess, onError);
});
};
function WebSQL(name) {
this.name = name || FILE_SYSTEM_NAME;
this.db = null;
}
WebSQL.isSupported = function() {
return !!global.openDatabase;
};
WebSQL.prototype.open = function(callback) {
var that = this;
// Bail if we already have a db open
if(that.db) {
return callback();
}
var db = global.openDatabase(that.name, WSQL_VERSION, WSQL_DESC, WSQL_SIZE);
if(!db) {
callback("[WebSQL] Unable to open database.");
return;
}
function onError(transaction, error) {
if (error.code === 5) {
callback(new Errors.EINVAL('WebSQL cannot be accessed. If private browsing is enabled, disable it.'));
}
callback(error);
}
function onSuccess(transaction, result) {
that.db = db;
callback();
}
// Create the table and index we'll need to store the fs data.
db.transaction(function(transaction) {
function createIndex(transaction) {
transaction.executeSql("CREATE INDEX IF NOT EXISTS idx_" + FILE_STORE_NAME + "_id" +
" on " + FILE_STORE_NAME + " (id);",
[], onSuccess, onError);
}
transaction.executeSql("CREATE TABLE IF NOT EXISTS " + FILE_STORE_NAME + " (id unique, data TEXT);",
[], createIndex, onError);
});
};
WebSQL.prototype.getReadOnlyContext = function() {
return new WebSQLContext(this.db, true);
};
WebSQL.prototype.getReadWriteContext = function() {
return new WebSQLContext(this.db, false);
};
module.exports = WebSQL;

View File

@ -1,26 +1,27 @@
function guid() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
function generateRandom(template) {
return template.replace(/[xy]/g, function(c) {
var r = Math.random()*16|0, v = c === 'x' ? r : (r&0x3|0x8);
return v.toString(16);
}).toUpperCase();
});
}
function guid() {
return generateRandom('xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx').toUpperCase();
}
/**
* Generate a string of n random characters. Defaults to n=6.
*/
function randomChars(n) {
n = n || 6;
var template = 'x'.repeat(n);
return generateRandom(template);
}
function nop() {}
/**
* Convert a Uint8Array to a regular array
*/
function u8toArray(u8) {
var array = [];
var len = u8.length;
for(var i = 0; i < len; i++) {
array[i] = u8[i];
}
return array;
}
module.exports = {
guid: guid,
u8toArray: u8toArray,
nop: nop
nop: nop,
randomChars: randomChars
};

View File

@ -1,4 +1,5 @@
var defaults = require('../constants.js').ENVIRONMENT;
'use strict';
const defaults = require('../constants.js').ENVIRONMENT;
module.exports = function Environment(env) {
env = env || {};

View File

@ -1,8 +1,9 @@
var {promisify} = require('es6-promisify');
var Path = require('../path.js');
var Errors = require('../errors.js');
var Environment = require('./environment.js');
var async = require('../../lib/async.js');
var Encoding = require('../encoding.js');
var minimatch = require('minimatch');
function Shell(fs, options) {
options = options || {};
@ -56,6 +57,24 @@ function Shell(fs, options) {
this.pwd = function() {
return cwd;
};
this.promises = {};
/**
* Public API for Shell converted to Promise based
*/
[
'cd',
'exec',
'touch',
'cat',
'ls',
'rm',
'tempDir',
'mkdirp',
'find'
].forEach((methodName)=>{
this.promises[methodName] = promisify(this[methodName].bind(this));
});
}
/**
@ -86,7 +105,7 @@ Shell.prototype.exec = function(path, args, callback) {
callback = callback || function(){};
path = Path.resolve(sh.pwd(), path);
fs.readFile(path, "utf8", function(error, data) {
fs.readFile(path, 'utf8', function(error, data) {
if(error) {
callback(error);
return;
@ -130,7 +149,7 @@ Shell.prototype.touch = function(path, options, callback) {
fs.utimes(path, atime, mtime, callback);
}
fs.stat(path, function(error, stats) {
fs.stat(path, function(error) {
if(error) {
if(options.updateOnly === true) {
callback();
@ -232,16 +251,10 @@ Shell.prototype.ls = function(dir, options, callback) {
callback(error);
return;
}
var entry = {
path: Path.basename(name),
links: stats.nlinks,
size: stats.size,
modified: stats.mtime,
type: stats.type
};
var entry = stats;
if(options.recursive && stats.type === 'DIRECTORY') {
list(Path.join(pathname, entry.path), function(error, items) {
list(Path.join(pathname, entry.name), function(error, items) {
if(error) {
callback(error);
return;
@ -353,7 +366,7 @@ Shell.prototype.tempDir = function(callback) {
// Try and create it, and it will either work or fail
// but either way it's now there.
fs.mkdir(tmp, function(err) {
fs.mkdir(tmp, function() {
callback(null, tmp);
});
};
@ -374,7 +387,8 @@ Shell.prototype.mkdirp = function(path, callback) {
callback(new Errors.EINVAL('Missing path argument'));
return;
}
else if (path === '/') {
path = Path.resolve(sh.pwd(), path);
if (path === '/') {
callback();
return;
}
@ -398,7 +412,7 @@ Shell.prototype.mkdirp = function(path, callback) {
var parent = Path.dirname(path);
if(parent === '/') {
fs.mkdir(path, function (err) {
if (err && err.code != 'EEXIST') {
if (err && err.code !== 'EEXIST') {
callback(err);
return;
}
@ -410,7 +424,7 @@ Shell.prototype.mkdirp = function(path, callback) {
_mkdirp(parent, function (err) {
if (err) return callback(err);
fs.mkdir(path, function (err) {
if (err && err.code != 'EEXIST') {
if (err && err.code !== 'EEXIST') {
callback(err);
return;
}
@ -426,4 +440,120 @@ Shell.prototype.mkdirp = function(path, callback) {
_mkdirp(path, callback);
};
/**
* Recursively walk a directory tree, reporting back all paths
* that were found along the way. The `path` must be a dir.
* Valid options include a `regex` for pattern matching paths
* and an `exec` function of the form `function(path, next)` where
* `path` is the current path that was found (dir paths have an '/'
* appended) and `next` is a callback to call when done processing
* the current path, passing any error object back as the first argument.
* `find` returns a flat array of absolute paths for all matching/found
* paths as the final argument to the callback.
*/
Shell.prototype.find = function(path, options, callback) {
var sh = this;
var fs = sh.fs;
if(typeof options === 'function') {
callback = options;
options = {};
}
options = options || {};
callback = callback || function(){};
var exec = options.exec || function(path, next) { next(); };
var found = [];
if(!path) {
callback(new Errors.EINVAL('Missing path argument'));
return;
}
function processPath(path, callback) {
exec(path, function(err) {
if(err) {
callback(err);
return;
}
found.push(path);
callback();
});
}
function maybeProcessPath(path, callback) {
// Test the path against the user's regex, name, path primaries (if any)
// and remove any trailing slashes added previously.
var rawPath = Path.removeTrailing(path);
// Check entire path against provided regex, if any
if(options.regex && !options.regex.test(rawPath)) {
callback();
return;
}
// Check basename for matches against name primary, if any
if(options.name && !minimatch(Path.basename(rawPath), options.name)) {
callback();
return;
}
// Check dirname for matches against path primary, if any
if(options.path && !minimatch(Path.dirname(rawPath), options.path)) {
callback();
return;
}
processPath(path, callback);
}
function walk(path, callback) {
path = Path.resolve(sh.pwd(), path);
// The path is either a file or dir, and instead of doing
// a stat() to determine it first, we just try to readdir()
// and it will either work or not, and we handle the non-dir error.
fs.readdir(path, function(err, entries) {
if(err) {
if(err.code === 'ENOTDIR' /* file case, ignore error */) {
maybeProcessPath(path, callback);
} else {
callback(err);
}
return;
}
// Path is really a dir, add a trailing / and report it found
maybeProcessPath(Path.addTrailing(path), function(err) {
if(err) {
callback(err);
return;
}
entries = entries.map(function(entry) {
return Path.join(path, entry);
});
async.eachSeries(entries, walk, function(err) {
callback(err, found);
});
});
});
}
// Make sure we are starting with a dir path
fs.stat(path, function(err, stats) {
if(err) {
callback(err);
return;
}
if(!stats.isDirectory()) {
callback(new Errors.ENOTDIR(null, path));
return;
}
walk(path, callback);
});
};
module.exports = Shell;

View File

@ -1,26 +1,43 @@
var Constants = require('./constants.js');
'use strict';
function Stats(fileNode, devName) {
this.node = fileNode.id;
const Constants = require('./constants.js');
const Path = require('./path.js');
function dateFromMs(ms) {
return new Date(Number(ms));
}
function Stats(path, fileNode, devName) {
this.dev = devName;
this.node = fileNode.id;
this.type = fileNode.type;
this.size = fileNode.size;
this.nlinks = fileNode.nlinks;
this.atime = fileNode.atime;
this.mtime = fileNode.mtime;
this.ctime = fileNode.ctime;
this.type = fileNode.mode;
// Date objects
this.atime = dateFromMs(fileNode.atime);
this.mtime = dateFromMs(fileNode.mtime);
this.ctime = dateFromMs(fileNode.ctime);
// Unix timestamp MS Numbers
this.atimeMs = fileNode.atime;
this.mtimeMs = fileNode.mtime;
this.ctimeMs = fileNode.ctime;
this.version = fileNode.version;
this.mode = fileNode.mode;
this.uid = fileNode.uid;
this.gid = fileNode.gid;
this.name = Path.basename(path);
}
Stats.prototype.isFile = function() {
return this.type === Constants.MODE_FILE;
return this.type === Constants.NODE_TYPE_FILE;
};
Stats.prototype.isDirectory = function() {
return this.type === Constants.MODE_DIRECTORY;
return this.type === Constants.NODE_TYPE_DIRECTORY;
};
Stats.prototype.isSymbolicLink = function() {
return this.type === Constants.MODE_SYMBOLIC_LINK;
return this.type === Constants.NODE_TYPE_SYMBOLIC_LINK;
};
// These will always be false in Filer.

View File

@ -4,7 +4,7 @@ function SuperNode(options) {
var now = Date.now();
this.id = Constants.SUPER_NODE_ID;
this.mode = Constants.MODE_META;
this.type = Constants.NODE_TYPE_META;
this.atime = options.atime || now;
this.ctime = options.ctime || now;
this.mtime = options.mtime || now;

View File

@ -0,0 +1,81 @@
var path = require('path');
var utils = require('./utils');
const PLUGIN_NAME = 'filer-webpack-plugin';
const OPTIONS_SCHEMA = require('./schema');
const OPTIONS_PROCESSORS = require('./processors');
module.exports = class FilerWebpackPlugin {
constructor(options = {}) {
utils.validateOptions(options, OPTIONS_SCHEMA);
this.options = utils.processOptions(options, OPTIONS_PROCESSORS);
}
apply(compiler) {
compiler.hooks.normalModuleFactory.tap(
PLUGIN_NAME,
(factory) => {
factory.hooks.resolve.tap(
PLUGIN_NAME,
(resolveData) => {
// Resolve fsProvider if required
if (
resolveData.request === 'fsProvider'
&& resolveData.context === this.options.shimsDir
) {
return this.resolveFsProvider(resolveData);
}
// Ignore filer files (these should resolve modules normally)
if (resolveData.context.startsWith(this.options.filerDir)) return;
// Apply fs, path and buffer shims if required
switch (resolveData.request) {
case 'fs':
if (!this.options.shimFs) return;
return this.applyFsShim(resolveData);
case 'path':
if (!this.options.shimPath) return;
return this.applyPathShim(resolveData);
default:
return;
}
}
);
},
);
}
resolveFsProvider(resolveData) {
switch (this.options.fsProvider) {
case 'default':
resolveData.request = path.join(this.options.fsProviderDir, 'default.js');
break;
case 'indexeddb':
resolveData.request = path.join(this.options.fsProviderDir, 'indexeddb.js');
break;
case 'memory':
resolveData.request = path.join(this.options.fsProviderDir, 'memory.js');
break;
case 'custom':
resolveData.request = path.join(this.options.fsProviderDir, 'custom.js');
break;
default:
throw new Error([
'Invalid option for fsProvider.',
'fsProvider must be one of \'default\', \'indexeddb\', \'memory\' or \'custom\'.',
'If using a custom fsProvider, you must also provide the fsProviderDir option.'
].join(' '));
}
}
applyFsShim(resolveData) {
resolveData.request = path.join(this.options.shimsDir, 'fs.js');
}
applyPathShim(resolveData) {
resolveData.request = path.join(this.options.shimsDir, 'path.js');
}
};

View File

@ -0,0 +1,34 @@
var path = require('path');
const ROOT_DIR_TAG = '<rootDir>';
const CWD = process.cwd();
module.exports = {
filerDir: {
process: function(value) {
if (!value) {
return path.join(CWD, 'node_modules', 'filer');
}
return path.resolve(value.replace(ROOT_DIR_TAG, CWD));
},
},
shimsDir: {
process: function(value) {
if (!value) {
return path.join(CWD, 'node_modules', 'filer', 'shims');
}
return path.resolve(value.replace(ROOT_DIR_TAG, CWD));
}
},
fsProviderDir: {
process: function(value) {
if (!value) {
return path.join(CWD, 'node_modules', 'filer', 'shims', 'providers');
}
return path.resolve(value.replace(ROOT_DIR_TAG, CWD));
},
},
shimFs: { default: true },
shimPath: { default: true},
fsProvider: { default: 'default'},
};

View File

@ -0,0 +1,23 @@
module.exports = {
type: 'object',
properties: {
filerDir: {
type: 'string',
},
shimsDir: {
type: 'string',
},
shimFs: {
type: 'boolean',
},
shimPath: {
type: 'boolean',
},
fsProvider: {
type: 'string',
},
fsProviderDir: {
type: 'string',
},
}
};

View File

@ -0,0 +1,26 @@
var { validate } = require('schema-utils');
function validateOptions(options, schema) {
validate(schema, options);
}
function processOptions(options, processors) {
const processedOptions = {};
for (const [property, processor] of Object.entries(processors)) {
processedOptions[property] = options[property];
if (processedOptions[property] === undefined) {
processedOptions[property] = processor.default;
}
if (processor.process) {
processedOptions[property] = processor.process(processedOptions[property]);
}
}
return processedOptions;
}
module.exports = {
validateOptions,
processOptions,
};

View File

@ -1,70 +0,0 @@
.highlight .hll { background-color: #ffffcc }
.highlight { background: #f0f3f3; }
.highlight .c { color: #0099FF; font-style: italic } /* Comment */
.highlight .err { color: #AA0000; background-color: #FFAAAA } /* Error */
.highlight .k { color: #006699; font-weight: bold } /* Keyword */
.highlight .o { color: #555555 } /* Operator */
.highlight .cm { color: #0099FF; font-style: italic } /* Comment.Multiline */
.highlight .cp { color: #009999 } /* Comment.Preproc */
.highlight .c1 { color: #0099FF; font-style: italic } /* Comment.Single */
.highlight .cs { color: #0099FF; font-weight: bold; font-style: italic } /* Comment.Special */
.highlight .gd { background-color: #FFCCCC; border: 1px solid #CC0000 } /* Generic.Deleted */
.highlight .ge { font-style: italic } /* Generic.Emph */
.highlight .gr { color: #FF0000 } /* Generic.Error */
.highlight .gh { color: #003300; font-weight: bold } /* Generic.Heading */
.highlight .gi { background-color: #CCFFCC; border: 1px solid #00CC00 } /* Generic.Inserted */
.highlight .go { color: #AAAAAA } /* Generic.Output */
.highlight .gp { color: #000099; font-weight: bold } /* Generic.Prompt */
.highlight .gs { font-weight: bold } /* Generic.Strong */
.highlight .gu { color: #003300; font-weight: bold } /* Generic.Subheading */
.highlight .gt { color: #99CC66 } /* Generic.Traceback */
.highlight .kc { color: #006699; font-weight: bold } /* Keyword.Constant */
.highlight .kd { color: #006699; font-weight: bold } /* Keyword.Declaration */
.highlight .kn { color: #006699; font-weight: bold } /* Keyword.Namespace */
.highlight .kp { color: #006699 } /* Keyword.Pseudo */
.highlight .kr { color: #006699; font-weight: bold } /* Keyword.Reserved */
.highlight .kt { color: #007788; font-weight: bold } /* Keyword.Type */
.highlight .m { color: #FF6600 } /* Literal.Number */
.highlight .s { color: #CC3300 } /* Literal.String */
.highlight .na { color: #330099 } /* Name.Attribute */
.highlight .nb { color: #336666 } /* Name.Builtin */
.highlight .nc { color: #00AA88; font-weight: bold } /* Name.Class */
.highlight .no { color: #336600 } /* Name.Constant */
.highlight .nd { color: #9999FF } /* Name.Decorator */
.highlight .ni { color: #999999; font-weight: bold } /* Name.Entity */
.highlight .ne { color: #CC0000; font-weight: bold } /* Name.Exception */
.highlight .nf { color: #CC00FF } /* Name.Function */
.highlight .nl { color: #9999FF } /* Name.Label */
.highlight .nn { color: #00CCFF; font-weight: bold } /* Name.Namespace */
.highlight .nt { color: #330099; font-weight: bold } /* Name.Tag */
.highlight .nv { color: #003333 } /* Name.Variable */
.highlight .ow { color: #000000; font-weight: bold } /* Operator.Word */
.highlight .w { color: #bbbbbb } /* Text.Whitespace */
.highlight .mf { color: #FF6600 } /* Literal.Number.Float */
.highlight .mh { color: #FF6600 } /* Literal.Number.Hex */
.highlight .mi { color: #FF6600 } /* Literal.Number.Integer */
.highlight .mo { color: #FF6600 } /* Literal.Number.Oct */
.highlight .sb { color: #CC3300 } /* Literal.String.Backtick */
.highlight .sc { color: #CC3300 } /* Literal.String.Char */
.highlight .sd { color: #CC3300; font-style: italic } /* Literal.String.Doc */
.highlight .s2 { color: #CC3300 } /* Literal.String.Double */
.highlight .se { color: #CC3300; font-weight: bold } /* Literal.String.Escape */
.highlight .sh { color: #CC3300 } /* Literal.String.Heredoc */
.highlight .si { color: #AA0000 } /* Literal.String.Interpol */
.highlight .sx { color: #CC3300 } /* Literal.String.Other */
.highlight .sr { color: #33AAAA } /* Literal.String.Regex */
.highlight .s1 { color: #CC3300 } /* Literal.String.Single */
.highlight .ss { color: #FFCC33 } /* Literal.String.Symbol */
.highlight .bp { color: #336666 } /* Name.Builtin.Pseudo */
.highlight .vc { color: #003333 } /* Name.Variable.Class */
.highlight .vg { color: #003333 } /* Name.Variable.Global */
.highlight .vi { color: #003333 } /* Name.Variable.Instance */
.highlight .il { color: #FF6600 } /* Literal.Number.Integer.Long */
.type-csharp .highlight .k { color: #0000FF }
.type-csharp .highlight .kt { color: #0000FF }
.type-csharp .highlight .nf { color: #000000; font-weight: normal }
.type-csharp .highlight .nc { color: #2B91AF }
.type-csharp .highlight .nn { color: #000000 }
.type-csharp .highlight .s { color: #A31515 }
.type-csharp .highlight .sc { color: #A31515 }

View File

@ -1,425 +0,0 @@
/*******************************************************************************
Slate Theme for GitHub Pages
by Jason Costello, @jsncostello
*******************************************************************************/
@import url(pygment_trac.css);
/*******************************************************************************
MeyerWeb Reset
*******************************************************************************/
html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed,
figure, figcaption, footer, header, hgroup,
menu, nav, output, ruby, section, summary,
time, mark, audio, video {
margin: 0;
padding: 0;
border: 0;
font: inherit;
vertical-align: baseline;
}
/* HTML5 display-role reset for older browsers */
article, aside, details, figcaption, figure,
footer, header, hgroup, menu, nav, section {
display: block;
}
ol, ul {
list-style: none;
}
table {
border-collapse: collapse;
border-spacing: 0;
}
/*******************************************************************************
Theme Styles
*******************************************************************************/
body {
box-sizing: border-box;
color:#373737;
background: #212121;
font-size: 16px;
font-family: 'Myriad Pro', Calibri, Helvetica, Arial, sans-serif;
line-height: 1.5;
-webkit-font-smoothing: antialiased;
}
h1, h2, h3, h4, h5, h6 {
margin: 10px 0;
font-weight: 700;
color:#222222;
font-family: 'Lucida Grande', 'Calibri', Helvetica, Arial, sans-serif;
letter-spacing: -1px;
}
h1 {
font-size: 36px;
font-weight: 700;
}
h2 {
padding-bottom: 10px;
font-size: 32px;
background: url('../images/bg_hr.png') repeat-x bottom;
}
h3 {
font-size: 24px;
}
h4 {
font-size: 21px;
}
h5 {
font-size: 18px;
}
h6 {
font-size: 16px;
}
p {
margin: 10px 0 15px 0;
}
footer p {
color: #f2f2f2;
}
a {
text-decoration: none;
color: #007edf;
text-shadow: none;
transition: color 0.5s ease;
transition: text-shadow 0.5s ease;
-webkit-transition: color 0.5s ease;
-webkit-transition: text-shadow 0.5s ease;
-moz-transition: color 0.5s ease;
-moz-transition: text-shadow 0.5s ease;
-o-transition: color 0.5s ease;
-o-transition: text-shadow 0.5s ease;
-ms-transition: color 0.5s ease;
-ms-transition: text-shadow 0.5s ease;
}
a:hover, a:focus {text-decoration: underline;}
footer a {
color: #F2F2F2;
text-decoration: underline;
}
em {
font-style: italic;
}
strong {
font-weight: bold;
}
img {
position: relative;
margin: 0 auto;
max-width: 739px;
padding: 5px;
margin: 10px 0 10px 0;
border: 1px solid #ebebeb;
box-shadow: 0 0 5px #ebebeb;
-webkit-box-shadow: 0 0 5px #ebebeb;
-moz-box-shadow: 0 0 5px #ebebeb;
-o-box-shadow: 0 0 5px #ebebeb;
-ms-box-shadow: 0 0 5px #ebebeb;
}
p img {
display: inline;
margin: 0;
padding: 0;
vertical-align: middle;
text-align: center;
border: none;
}
pre, code {
width: 100%;
color: #222;
background-color: #fff;
font-family: Monaco, "Bitstream Vera Sans Mono", "Lucida Console", Terminal, monospace;
font-size: 14px;
border-radius: 2px;
-moz-border-radius: 2px;
-webkit-border-radius: 2px;
}
pre {
width: 100%;
padding: 10px;
box-shadow: 0 0 10px rgba(0,0,0,.1);
overflow: auto;
}
code {
padding: 3px;
margin: 0 3px;
box-shadow: 0 0 10px rgba(0,0,0,.1);
}
pre code {
display: block;
box-shadow: none;
}
blockquote {
color: #666;
margin-bottom: 20px;
padding: 0 0 0 20px;
border-left: 3px solid #bbb;
}
ul, ol, dl {
margin-bottom: 15px
}
ul {
list-style-position: inside;
list-style: disc;
padding-left: 20px;
}
ol {
list-style-position: inside;
list-style: decimal;
padding-left: 20px;
}
dl dt {
font-weight: bold;
}
dl dd {
padding-left: 20px;
font-style: italic;
}
dl p {
padding-left: 20px;
font-style: italic;
}
hr {
height: 1px;
margin-bottom: 5px;
border: none;
background: url('../images/bg_hr.png') repeat-x center;
}
table {
border: 1px solid #373737;
margin-bottom: 20px;
text-align: left;
}
th {
font-family: 'Lucida Grande', 'Helvetica Neue', Helvetica, Arial, sans-serif;
padding: 10px;
background: #373737;
color: #fff;
}
td {
padding: 10px;
border: 1px solid #373737;
}
form {
background: #f2f2f2;
padding: 20px;
}
/*******************************************************************************
Full-Width Styles
*******************************************************************************/
.outer {
width: 100%;
}
.inner {
position: relative;
max-width: 640px;
padding: 20px 10px;
margin: 0 auto;
}
#forkme_banner {
display: block;
position: absolute;
top:0;
right: 10px;
z-index: 10;
padding: 10px 50px 10px 10px;
color: #fff;
background: url('../images/blacktocat.png') #0090ff no-repeat 95% 50%;
font-weight: 700;
box-shadow: 0 0 10px rgba(0,0,0,.5);
border-bottom-left-radius: 2px;
border-bottom-right-radius: 2px;
}
#header_wrap {
background: #212121;
background: -moz-linear-gradient(top, #373737, #212121);
background: -webkit-linear-gradient(top, #373737, #212121);
background: -ms-linear-gradient(top, #373737, #212121);
background: -o-linear-gradient(top, #373737, #212121);
background: linear-gradient(top, #373737, #212121);
}
#header_wrap .inner {
padding: 50px 10px 30px 10px;
}
#project_title {
margin: 0;
color: #fff;
font-size: 42px;
font-weight: 700;
text-shadow: #111 0px 0px 10px;
}
#project_tagline {
color: #fff;
font-size: 24px;
font-weight: 300;
background: none;
text-shadow: #111 0px 0px 10px;
}
#downloads {
position: absolute;
width: 210px;
z-index: 10;
bottom: -40px;
right: 0;
height: 70px;
background: url('../images/icon_download.png') no-repeat 0% 90%;
}
.zip_download_link {
display: block;
float: right;
width: 90px;
height:70px;
text-indent: -5000px;
overflow: hidden;
background: url(../images/sprite_download.png) no-repeat bottom left;
}
.tar_download_link {
display: block;
float: right;
width: 90px;
height:70px;
text-indent: -5000px;
overflow: hidden;
background: url(../images/sprite_download.png) no-repeat bottom right;
margin-left: 10px;
}
.zip_download_link:hover {
background: url(../images/sprite_download.png) no-repeat top left;
}
.tar_download_link:hover {
background: url(../images/sprite_download.png) no-repeat top right;
}
#main_content_wrap {
background: #f2f2f2;
border-top: 1px solid #111;
border-bottom: 1px solid #111;
}
#main_content {
padding-top: 40px;
}
#footer_wrap {
background: #212121;
}
/*******************************************************************************
Small Device Styles
*******************************************************************************/
@media screen and (max-width: 480px) {
body {
font-size:14px;
}
#downloads {
display: none;
}
.inner {
min-width: 320px;
max-width: 480px;
}
#project_title {
font-size: 32px;
}
h1 {
font-size: 28px;
}
h2 {
font-size: 24px;
}
h3 {
font-size: 21px;
}
h4 {
font-size: 18px;
}
h5 {
font-size: 14px;
}
h6 {
font-size: 12px;
}
code, pre {
min-width: 320px;
max-width: 480px;
font-size: 11px;
}
}

View File

@ -1,4 +1,3 @@
var Filer = require('../..');
var util = require('../lib/test-utils.js');
var expect = require('chai').expect;

View File

@ -1,4 +1,3 @@
var Filer = require('../..');
var util = require('../lib/test-utils.js');
var expect = require('chai').expect;

View File

@ -1,44 +0,0 @@
/**
* https://github.com/js-platform/filer/pull/225
*
* NOTE: this test has to be run outside the browserify step,
* since combinining require for node.js/browserify builds with
* r.js doesn't work.
*/
var requirejs = require('requirejs');
var expect = require('chai').expect;
// browser-request assumes access to XHR
GLOBAL.XMLHttpRequest = {};
describe('require.js should be able to use built Filer, issue 225', function() {
it('should properly load Filer as an AMD module, with Buffer included', function(done) {
requirejs.config({
baseUrl: __dirname,
paths: {
"filer": "../../dist/filer-issue225"
},
nodeRequire: require
});
requirejs(["filer"], function(Filer) {
expect(Filer).to.exist;
expect(Filer.Buffer).to.exist;
var fs = new Filer.FileSystem({provider: new Filer.FileSystem.providers.Memory()});
var buf = new Filer.Buffer([1, 2, 3]);
fs.writeFile('/file', buf, function(err) {
expect(err).not.to.exist;
fs.readFile('/file', function(err, data) {
expect(err).not.to.exist;
expect(data).to.deep.equal(buf);
done();
});
});
});
});
});

View File

@ -1,4 +1,3 @@
var Filer = require('../..');
var util = require('../lib/test-utils.js');
var expect = require('chai').expect;

View File

@ -1,4 +1,3 @@
var Filer = require('../..');
var util = require('../lib/test-utils.js');
var expect = require('chai').expect;

View File

@ -1,4 +1,4 @@
var Filer = require('../..');
var Filer = require('../../src');
var util = require('../lib/test-utils.js');
var expect = require('chai').expect;
@ -7,7 +7,7 @@ describe('Filer.Buffer should accept initialized ArrayBuffers, issue 249', funct
afterEach(util.cleanup);
it('should accept an ArrayBuffer with a specified size', function(done) {
var buffer = new Filer.Buffer(new ArrayBuffer(5));
var buffer = Buffer.from(new ArrayBuffer(5));
expect(buffer.length).to.equal(5);
done();
});
@ -18,7 +18,7 @@ describe('Filer.Buffer static methods are in tact, issue 249', function() {
afterEach(util.cleanup);
it('should proxy Buffer.isBuffer', function(done) {
expect(Filer.Buffer.isBuffer(new Filer.Buffer([]))).to.equal(true);
expect(Filer.Buffer.isBuffer(Buffer.from([]))).to.equal(true);
expect(Filer.Buffer.isBuffer('')).to.equal(false);
done();
});
@ -35,7 +35,7 @@ describe('Filer.Buffer static methods are in tact, issue 249', function() {
});
it('should proxy Buffer.concat', function(done) {
expect(Filer.Buffer.concat([new Filer.Buffer(1), new Filer.Buffer(2)]).length).to.equal(3);
expect(Filer.Buffer.concat([Buffer.alloc(1), Buffer.alloc(2)]).length).to.equal(3);
done();
});
});

View File

@ -1,4 +1,3 @@
var Filer = require('../..');
var util = require('../lib/test-utils.js');
var expect = require('chai').expect;

View File

@ -1,5 +1,4 @@
var Filer = require('../..');
var util = require('../lib/test-utils.js');
var Filer = require('../../src');
var expect = require('chai').expect;
var setImmediate = require('../../lib/async.js').setImmediate;
@ -53,7 +52,9 @@ describe('Queued operations should error when fs is in error state, issue 258',
it('should get EFILESYSTEMERROR errors on callbacks to queued operations on provider error', function(done) {
var errCount = 0;
var fs = new Filer.FileSystem({provider: provider});
var fs = new Filer.FileSystem({provider: provider}, function() {
// Do nothing
});
function maybeDone(err) {
expect(err).to.exist;

View File

@ -1,4 +1,3 @@
var Filer = require('../..');
var util = require('../lib/test-utils.js');
var expect = require('chai').expect;
@ -15,6 +14,7 @@ describe('fs.readdir on non-dir paths, issue 267', function() {
fs.readdir('/myfile.txt', function(err, contents) {
expect(err).to.exist;
expect(err.code).to.equal('ENOTDIR');
expect(contents).not.to.exist;
done();
});
});

View File

@ -1,4 +1,3 @@
var Filer = require('../..');
var util = require('../lib/test-utils.js');
var expect = require('chai').expect;
@ -6,23 +5,15 @@ describe('undefined and relative paths, issue270', function() {
beforeEach(util.setup);
afterEach(util.cleanup);
it('should fail with EINVAL when called on an undefined path', function(done) {
it('should fail with EINVAL when called on an undefined path', function() {
var fs = util.fs();
fs.writeFile(undefined, 'data', function(err) {
expect(err).to.exist;
expect(err.code).to.equal('EINVAL');
done();
});
var fn = () => fs.writeFile(undefined, 'data');
expect(fn).to.throw();
});
it('should fail with EINVAL when called on a relative path', function(done) {
it('should fail with EINVAL when called on a relative path', function() {
var fs = util.fs();
fs.writeFile('relpath/file.txt', 'data', function(err) {
expect(err).to.exist;
expect(err.code).to.equal('EINVAL');
done();
});
var fn = () => fs.writeFile('relpath/file.txt', 'data');
expect(fn).to.throw();
});
});

17
tests/bugs/issue357.js Normal file
View File

@ -0,0 +1,17 @@
var Path = require('../../src').Path;
var expect = require('chai').expect;
describe('Path.resolve does not work, issue357', function() {
it('Path.relative() should not crash', function() {
expect(Path.relative('/mydir', '/mydir/file')).to.equal('file');
// https://nodejs.org/api/path.html#path_path_relative_from_to
expect(Path.relative('/data/orandea/test/aaa', '/data/orandea/impl/bbb')).to.equal('../../impl/bbb');
});
it('Path.resolve() should work as expectedh', function() {
// https://nodejs.org/api/path.html#path_path_resolve_from_to
expect(Path.resolve('/foo/bar', './baz')).to.equal('/foo/bar/baz');
expect(Path.resolve('/foo/bar', '/tmp/file/')).to.equal('/tmp/file');
});
});

12
tests/bugs/issue773.js Normal file
View File

@ -0,0 +1,12 @@
'use strict';
const util = require('../lib/test-utils.js');
describe('unexpected failures when calling fs functions (e.g. writeFile) with empty options object, issue 773', function() {
beforeEach(util.setup);
afterEach(util.cleanup);
it('should call fs.writeFile with an empty options object', function(done) {
const fs = util.fs();
fs.writeFile('/a', 'trololol', {}, done);
});
});

115
tests/bugs/issue775.js Normal file
View File

@ -0,0 +1,115 @@
'use strict';
var util = require('../lib/test-utils.js');
var expect = require('chai').expect;
describe('fs.readdir fails when passing options, issue775', function () {
beforeEach(util.setup);
afterEach(util.cleanup);
function setup(fs, dir, cb) {
fs.mkdir(dir, undefined, (err) => {
if (err) {
cb(err);
}
else {
fs.writeFile(dir + '/file', '', (err) => {
if (err) {
cb(err);
}
else {
fs.mkdir(dir + '/folder', (err) => {
if (err) {
cb(err);
}
else {
fs.symlink(dir + '/file', dir + '/symlink', (err) => {
if (err) {
cb(err);
}
else {
cb();
}
});
}
});
}
});
}
});
}
it('should create a directory, add a file, folder and symbolic link then call fs.readdir with buffer encoding', function (done) {
var fs = util.fs();
setup(fs, '/test_dir', (err) => {
if (err) {
done(err);
}
fs.readdir('/test_dir', 'buffer', (err, data) => {
if (err) {
done(err);
}
else {
expect(data).to.have.length(3);
expect(data[0].toString()).to.equal('file');
expect(data[1].toString()).to.equal('folder');
expect(data[2].toString()).to.equal('symlink');
done();
}
});
});
});
it('should create a directory, add a file, folder and symbolic link then call fs.readdir with withFileTypes and encoding options', function (done) {
var fs = util.fs();
setup(fs, '/test_dir', (err) => {
if (err) {
done(err);
}
fs.readdir('/test_dir', { encoding: 'base64', withFileTypes: true }, (err, data) => {
if (err) {
done(err);
}
else {
expect(data).to.have.length(3);
expect(Buffer.from(data[0].name, 'base64').toString()).to.equal('file');
expect(Buffer.from(data[1].name, 'base64').toString()).to.equal('folder');
expect(Buffer.from(data[2].name, 'base64').toString()).to.equal('symlink');
expect(data[0].isFile()).to.be.true;
expect(data[1].isDirectory()).to.be.true;
expect(data[2].isSymbolicLink()).to.be.true;
done();
}
});
});
});
it('should create a directory then call fs.readdir without options', function (done) {
var fs = util.fs();
setup(fs, '/test_dir', (err) => {
if (err) {
done(err);
}
else {
fs.readdir('/test_dir', (err, data) => {
if (err) {
done(err);
}
else {
expect(data).to.have.length(3);
expect(data[0]).to.equal('file');
expect(data[1]).to.equal('folder');
expect(data[2]).to.equal('symlink');
done();
}
});
}
});
});
});

12
tests/bugs/issue776.js Normal file
View File

@ -0,0 +1,12 @@
'use strict';
const util = require('../lib/test-utils.js');
describe('fs.mkdir does not recursively create parent directories when called with { recursive: true }, issue776', function() {
beforeEach(util.setup);
afterEach(util.cleanup);
it.skip('should not throw when calling fs.mkdir with recursive flag set', function(done) {
const fs = util.fs();
fs.mkdir('/test_dir/a/b', { recursive: true }, done);
});
});

View File

@ -1,4 +1,4 @@
var Filer = require('../..');
var Filer = require('../../src');
var util = require('../lib/test-utils.js');
var expect = require('chai').expect;
var async = require('../../lib/async.js');
@ -25,7 +25,7 @@ describe('sh.ls and deep directory trees', function() {
done();
});
});
});
}).timeout(15000);
it('should not crash when calling sh.ls() on wide directory layouts', function(done) {
var fs = util.fs();
@ -46,7 +46,7 @@ describe('sh.ls and deep directory trees', function() {
}
async.eachSeries(paths, writeFile, function(err) {
if(err) { console.log('error', err); throw err; }
if(err) throw err;
sh.ls('/', {recursive: true}, function(err, listing) {
expect(err).not.to.exist;
@ -55,5 +55,5 @@ describe('sh.ls and deep directory trees', function() {
});
});
});
});
}).timeout(15000);
});

View File

@ -0,0 +1,27 @@
var util = require('../lib/test-utils.js');
var expect = require('chai').expect;
describe('trailing slashes in path names to work when renaming a dir', function() {
beforeEach(util.setup);
afterEach(util.cleanup);
it('should deal with trailing slashes in rename, dir == dir/', function(done) {
var fs = util.fs();
fs.mkdir('/tmp', function(err) {
if(err) throw err;
fs.rename('/tmp/', '/new-tmp/', function(err) {
if(err) throw err;
fs.stat('/new-tmp', function(err, stats) {
if(err) throw err;
expect(stats).to.exist;
expect(stats.isDirectory()).to.be.true;
done();
});
});
});
});
});

View File

@ -0,0 +1,9 @@
The following images are JSON filesystem images created with
`tools/fs-image.js`, and named with the filesystem dir used
as the source of the image, and the version of Filer used to
generate them:
1. `tiny-fs.0.43.json` was created from `tests/filesystem/tiny-fs/` with https://github.com/filerjs/filer/blob/d66114e20c7f0235698d9933dbd90217ba86fa4e/dist/filer.min.js
If you need to create a new image, use `tools/get-filer-version.js` to
get a specific version of Filer, then `tools/fs-image.js` to generate an image.

View File

@ -0,0 +1 @@
{"00000000-0000-0000-0000-000000000000":{"id":"00000000-0000-0000-0000-000000000000","mode":"META","atime":1545098425757,"ctime":1545098425757,"mtime":1545098425757,"rnode":"A63180BA-9BCE-4245-86E8-8613726587CA"},"A63180BA-9BCE-4245-86E8-8613726587CA":{"id":"A63180BA-9BCE-4245-86E8-8613726587CA","mode":"DIRECTORY","size":0,"atime":1545098425770,"ctime":1545098425770,"mtime":1545098425770,"flags":[],"xattrs":{},"nlinks":1,"version":0,"nblocks":1,"data":"3A41160B-1F39-4162-85BD-473F16ABF35F"},"3A41160B-1F39-4162-85BD-473F16ABF35F":{"dir":{"id":"E1634C88-337D-4D1E-9155-81B099BC7E7C","type":"DIRECTORY"},"file.txt":{"id":"DD338D5C-34FF-4AF7-AFBB-C01E8214125F","type":"FILE"}},"E1634C88-337D-4D1E-9155-81B099BC7E7C":{"id":"E1634C88-337D-4D1E-9155-81B099BC7E7C","mode":"DIRECTORY","size":0,"atime":1545098425778,"ctime":1545098425778,"mtime":1545098425778,"flags":[],"xattrs":{},"nlinks":1,"version":0,"nblocks":1,"data":"C8BB5894-9B0C-4CDC-B014-3944FB40DA77"},"C8BB5894-9B0C-4CDC-B014-3944FB40DA77":{"file2.txt":{"id":"EEB56FEC-DABE-48BF-88A5-B9F37723A0BC","type":"FILE"}},"DD338D5C-34FF-4AF7-AFBB-C01E8214125F":{"id":"DD338D5C-34FF-4AF7-AFBB-C01E8214125F","mode":"FILE","size":16,"atime":1545098327877.7542,"ctime":1545098313562.6824,"mtime":1545098313562.6824,"flags":[],"xattrs":{},"nlinks":1,"version":1,"nblocks":1,"data":"BDEE2339-6992-4D8F-AFAA-81813C30592C"},"BDEE2339-6992-4D8F-AFAA-81813C30592C":{"type":"Buffer","data":[84,104,105,115,32,105,115,32,97,32,102,105,108,101,46,10]},"EEB56FEC-DABE-48BF-88A5-B9F37723A0BC":{"id":"EEB56FEC-DABE-48BF-88A5-B9F37723A0BC","mode":"FILE","size":23,"atime":1545098327877.7542,"ctime":1545098313562.6824,"mtime":1545098313562.6824,"flags":[],"xattrs":{},"nlinks":1,"version":1,"nblocks":1,"data":"62262B53-32BC-43F6-983B-4127302C2483"},"62262B53-32BC-43F6-983B-4127302C2483":{"type":"Buffer","data":[84,104,105,115,32,105,115,32,97,32,115,101,99,111,110,100,32,102,105,108,101,46,10]}}

View File

@ -0,0 +1,91 @@
const expect = require('chai').expect;
const Filer = require('../../../src');
const SerializableMemoryProvider = require('../../lib/serializable-memory-provider');
const nodeFs = require('fs');
const nodePath = require('path');
describe('Migration tests from Filer 0.43 to current', () => {
let filerFs;
before(done => {
// Let the provider parse the JSON
const imagePath = nodePath.resolve(__dirname, '../images/tiny-fs.0.43.json');
nodeFs.readFile(imagePath, 'utf8', (err, data) => {
if(err) throw err;
new Filer.FileSystem({
provider: new SerializableMemoryProvider('0.43', data)
}, (err, fs) => {
if(err) throw err;
filerFs = fs;
done();
});
});
});
it('should have a root directory', done => {
filerFs.stat('/', (err, stats) => {
if(err) throw err;
expect(stats).to.be.an('object');
expect(stats.isDirectory()).to.be.true;
done();
});
});
it('should have expected entries in root dir', done => {
filerFs.readdir('/', (err, entries) => {
if(err) throw err;
expect(entries).to.be.an('array');
expect(entries.length).to.equal(2);
expect(entries).to.contain('file.txt');
expect(entries).to.contain('dir');
done();
});
});
it('should have correct contents for /file.txt (read as String)', done => {
const fileTxtPath = nodePath.resolve(__dirname, '../tiny-fs/file.txt');
nodeFs.readFile(fileTxtPath, 'utf8', (err, nodeData) => {
if(err) throw err;
filerFs.readFile('/file.txt', 'utf8', (err, filerData) => {
if(err) throw err;
expect(nodeData).to.equal(filerData);
done();
});
});
});
it('should have expected entries in /dir', done => {
filerFs.readdir('/dir', (err, entries) => {
if(err) throw err;
expect(entries).to.be.an('array');
expect(entries.length).to.equal(1);
expect(entries).to.contain('file2.txt');
done();
});
});
it('should have correct contents for /dir/file2.txt (read as Buffer)', done => {
const file2TxtPath = nodePath.resolve(__dirname, '../tiny-fs/dir/file2.txt');
nodeFs.readFile(file2TxtPath, null, (err, nodeData) => {
if(err) throw err;
filerFs.readFile('/dir/file2.txt', null, (err, filerData) => {
if(err) throw err;
expect(nodeData).to.deep.equal(filerData);
done();
});
});
});
});

View File

@ -0,0 +1 @@
This is a second file.

View File

@ -0,0 +1 @@
This is a file.

View File

@ -1,24 +1,26 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Mocha Tests</title>
<title>Filer Tests</title>
<link rel="stylesheet" href="../node_modules/mocha/mocha.css" />
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/mocha/1.21.4/mocha.css" />
<script src="//cdnjs.cloudflare.com/ajax/libs/mocha/1.21.4/mocha.js"></script>
<script>window.mocha || document.write('<script src="../node_modules/mocha/mocha.js"><\/script>')</script>
<script src="//cdnjs.cloudflare.com/ajax/libs/chai/1.9.2/chai.min.js"></script>
<script>window.chai || document.write('<script src="../node_modules/chai/chai.js"><\/script>')</script>
</head>
<body>
<div id="mocha"></div>
<script src="../node_modules/chai/chai.js"></script>
<script src="../node_modules/mocha/mocha.js"></script>
<script>
mocha.setup('bdd').timeout(5000).slow(250);;
mocha.setup('bdd').timeout(10000).slow(250);
window.onload = function() {
mocha.checkLeaks();
mocha.run();
};
</script>
<script src="../dist/filer-test.js"></script>
</head>
<body>
<div id="mocha"></div>
<!-- Add any new tests to `tests/index.js` -->
<script src="./index.js"></script>
</body>
</html>

View File

@ -3,75 +3,97 @@
* get them running by default.
*/
// Shims
require('./spec/shims/fs.spec');
require('./spec/shims/path.spec');
// Webpack Plugin
require('./spec/webpack-plugin/webpack-plugin.spec');
// Filer
require("./spec/filer.spec");
require('./spec/filer.spec');
require('./spec/filer.buffer.spec.js');
// Filer.FileSystem.*
require("./spec/filer.filesystem.spec");
require("./spec/fs.spec");
require("./spec/fs.stat.spec");
require("./spec/fs.lstat.spec");
require("./spec/fs.exists.spec");
require("./spec/fs.mknod.spec");
require("./spec/fs.mkdir.spec");
require("./spec/fs.readdir.spec");
require("./spec/fs.rmdir.spec");
require("./spec/fs.open.spec");
require("./spec/fs.write.spec");
require("./spec/fs.writeFile-readFile.spec");
require("./spec/fs.appendFile.spec");
require("./spec/fs.read.spec");
require("./spec/fs.close.spec");
require("./spec/fs.link.spec");
require("./spec/fs.unlink.spec");
require("./spec/fs.rename.spec");
require("./spec/fs.lseek.spec");
require("./spec/fs.symlink.spec");
require("./spec/fs.readlink.spec");
require("./spec/fs.truncate.spec");
require("./spec/fs.utimes.spec");
require("./spec/fs.xattr.spec");
require("./spec/fs.stats.spec");
require("./spec/path-resolution.spec");
require("./spec/trailing-slashes.spec");
require("./spec/times.spec");
require("./spec/time-flags.spec");
require("./spec/fs.watch.spec");
require("./spec/errors.spec");
require("./spec/fs.shell.spec");
require('./spec/filer.filesystem.spec');
require('./spec/fs.spec');
require('./spec/fs.access.spec');
require('./spec/fs.stat.spec');
require('./spec/fs.lstat.spec');
require('./spec/fs.exists.spec');
require('./spec/fs.mknod.spec');
require('./spec/fs.mkdir.spec');
require('./spec/fs.mkdtemp.spec');
require('./spec/fs.readdir.spec');
require('./spec/fs.rmdir.spec');
require('./spec/fs.open.spec');
require('./spec/fs.write.spec');
require('./spec/fs.writeFile-readFile.spec');
require('./spec/fs.appendFile.spec');
require('./spec/fs.read.spec');
require('./spec/fs.close.spec');
require('./spec/fs.fsync.spec');
require('./spec/fs.link.spec');
require('./spec/fs.unlink.spec');
require('./spec/fs.rename.spec');
require('./spec/fs.lseek.spec');
require('./spec/fs.symlink.spec');
require('./spec/fs.readlink.spec');
require('./spec/fs.truncate.spec');
require('./spec/fs.ftruncate.spec');
require('./spec/fs.utimes.spec');
require('./spec/fs.xattr.spec');
require('./spec/path-resolution.spec');
require('./spec/trailing-slashes.spec');
require('./spec/times.spec');
require('./spec/time-flags.spec');
require('./spec/fs.watch.spec');
require('./spec/fs.unwatchFile.spec');
require('./spec/errors.spec');
require('./spec/fs.shell.spec');
require('./spec/fs.chmod.spec');
require('./spec/fs.chown.spec');
require('./spec/fs.copyFile.spec');
// Filer.FileSystem.providers.*
require("./spec/providers/providers.spec");
require("./spec/providers/providers.indexeddb.spec");
require("./spec/providers/providers.websql.spec");
require("./spec/providers/providers.memory.spec");
require('./spec/providers/providers.spec');
require('./spec/providers/providers.indexeddb.spec');
require('./spec/providers/providers.memory.spec');
require('./spec/providers/serializable-memory-provider.spec');
// Filer.FileSystemShell.*
require("./spec/shell/cd.spec");
require("./spec/shell/touch.spec");
require("./spec/shell/exec.spec");
require("./spec/shell/cat.spec");
require("./spec/shell/ls.spec");
require("./spec/shell/rm.spec");
require("./spec/shell/env.spec");
require("./spec/shell/mkdirp.spec");
require("./spec/shell/find.spec");
require('./spec/shell/cd.spec');
require('./spec/shell/touch.spec');
require('./spec/shell/exec.spec');
require('./spec/shell/cat.spec');
require('./spec/shell/ls.spec');
require('./spec/shell/rm.spec');
require('./spec/shell/env.spec');
require('./spec/shell/mkdirp.spec');
require('./spec/shell/find.spec');
// Ported node.js tests (filenames match names in https://github.com/joyent/node/tree/master/test)
require("./spec/node-js/simple/test-fs-mkdir");
require("./spec/node-js/simple/test-fs-null-bytes");
require("./spec/node-js/simple/test-fs-watch");
require("./spec/node-js/simple/test-fs-watch-recursive");
require('./spec/node-js/simple/test-fs-mkdir');
require('./spec/node-js/simple/test-fs-null-bytes');
require('./spec/node-js/simple/test-fs-watch');
require('./spec/node-js/simple/test-fs-watch-recursive');
// Regressions, Bugs
// NOTE: bugs/issue225.js has to be run outside this step, see gruntfile.js
require("./bugs/issue105");
require("./bugs/issue106");
require("./bugs/issue239");
require("./bugs/issue249");
require("./bugs/ls-depth-bug");
require("./bugs/issue247.js");
require("./bugs/issue254.js");
require("./bugs/issue258.js");
require("./bugs/issue267.js");
require("./bugs/issue270.js");
require('./bugs/issue105');
require('./bugs/issue106');
require('./bugs/issue239');
require('./bugs/issue249');
require('./bugs/ls-depth-bug');
require('./bugs/issue247.js');
require('./bugs/issue254.js');
require('./bugs/issue258.js');
require('./bugs/issue267.js');
require('./bugs/issue270.js');
require('./bugs/rename-dir-trailing-slash.js');
require('./bugs/issue357.js');
require('./bugs/issue773.js');
require('./bugs/issue775.js');
require('./bugs/issue776.js');
// Sample code from README
require('./spec/readme.example.spec');

View File

@ -1,11 +1,8 @@
var Filer = require("../..");
'use strict';
var indexedDB = global.indexedDB ||
global.mozIndexedDB ||
global.webkitIndexedDB ||
global.msIndexedDB;
const Filer = require('../../src');
var needsCleanup = [];
let needsCleanup = [];
if(global.addEventListener) {
global.addEventListener('beforeunload', function() {
needsCleanup.forEach(function(f) { f(); });
@ -13,8 +10,8 @@ if(global.addEventListener) {
}
function IndexedDBTestProvider(name) {
var _done = false;
var that = this;
let _done = false;
let that = this;
function cleanup(callback) {
callback = callback || function(){};
@ -23,20 +20,32 @@ function IndexedDBTestProvider(name) {
return callback();
}
// We have to force any other connections to close
// before we can delete a db.
if(that.provider.db) {
that.provider.db.close();
}
var request = indexedDB.deleteDatabase(name);
function finished() {
that.provider = null;
_done = true;
callback();
}
request.onsuccess = finished;
request.onerror = finished;
try {
// We have to force any other connections to close
// before we can delete a db.
if(that.provider.db) {
that.provider.db.close();
}
const indexedDB = global.indexedDB ||
global.mozIndexedDB ||
global.webkitIndexedDB ||
global.msIndexedDB;
let request = indexedDB.deleteDatabase(name);
request.onsuccess = finished;
request.onerror = finished;
} catch(e) {
/* eslint no-console:0 */
console.log('Failed to delete test database', e);
finished();
}
}
function init() {

View File

@ -1,4 +1,4 @@
var Filer = require('../..');
var Filer = require('../../src');
function MemoryTestProvider(name) {
var that = this;

View File

@ -0,0 +1,42 @@
const MemoryProvider = require('../../src/providers/memory');
const { parseBJSON } = require('../lib/test-utils');
class SerializableMemoryProvider extends MemoryProvider {
constructor(name, jsonImage) {
super(name);
this.unparsedJSONImage = jsonImage;
}
/**
* In addition to the usual setup of a Memory provider,
* also parse and overwrite the internal database.
*/
open(callback) {
super.open(err => {
if(err) {
return callback(err);
}
// If we don't have an image to import, leave db as is
if(!this.unparsedJSONImage) {
return callback();
}
// Try to import the fs image from JSON
try {
this.db = parseBJSON(this.unparsedJSONImage);
this.unparsedJSONImage = null;
callback();
} catch(e) {
callback(new Error(`unable to parse JSON filesystem image: ${e.message}`));
}
});
}
export() {
return JSON.stringify(this.db);
}
}
module.exports = SerializableMemoryProvider;

View File

@ -1,135 +1,195 @@
(function(global) {
var Filer = require('../../src');
var IndexedDBTestProvider = require('./indexeddb.js');
var MemoryTestProvider = require('./memory.js');
var Url = require('url');
var Filer = require('../..');
var IndexedDBTestProvider = require('./indexeddb.js');
var WebSQLTestProvider = require('./websql.js');
var MemoryTestProvider = require('./memory.js');
var _provider;
var _fs;
var _provider;
var _fs;
function uniqueName() {
if(!uniqueName.seed) {
uniqueName.seed = Date.now();
}
return 'filer-testdb-' + uniqueName.seed++;
}
function uniqueName() {
if(!uniqueName.seed) {
uniqueName.seed = Date.now();
}
return 'filer-testdb-' + uniqueName.seed++;
function findBestProvider() {
var providers = Filer.FileSystem.providers;
return providers.IndexedDB.isSupported() ?
IndexedDBTestProvider : MemoryTestProvider;
}
function getUrlParams() {
// Check if we are running in node
if(!global.location) {
return null;
}
function findBestProvider() {
var providers = Filer.FileSystem.providers;
if(providers.IndexedDB.isSupported()) {
return IndexedDBTestProvider;
}
if(providers.WebSQL.isSupported()) {
return WebSQLTestProvider;
}
return MemoryTestProvider;
var url = Url.parse(global.location.href, true);
return url.query;
}
function getProviderType() {
var defaultProvider = 'default';
var queryString = getUrlParams();
// If the environment is node or the query string is empty,
// the memory provider will be used.
if(!queryString) {
return defaultProvider;
}
function setup(callback) {
// In browser we support specifying the provider via the query string
// (e.g., ?filer-provider=IndexedDB). If not specified, we use
// the Memory provider by default. See test/require-config.js
// for definition of window.filerArgs.
var providerType = global.filerArgs && global.filerArgs.provider ?
global.filerArgs.provider : 'Memory';
return queryString['filer-provider'] || defaultProvider;
}
var name = uniqueName();
// Run fn() in an environment with indexedDB available
// either as-is, or shimmed, removing when done.
function shimIndexedDB(fn) {
var addShim = !Filer.FileSystem.providers.IndexedDB.isSupported();
switch(providerType.toLowerCase()) {
case 'indexeddb':
_provider = new IndexedDBTestProvider(name);
break;
case 'websql':
_provider = new WebSQLTestProvider(name);
break;
case 'memory':
/* falls through */
default:
var BestProvider = findBestProvider();
_provider = new BestProvider(name);
break;
}
// Allow passing FS flags on query string
var flags = global.filerArgs && global.filerArgs.flags ?
global.filerArgs.flags : 'FORMAT';
// Create a file system and wait for it to get setup
_provider.init();
function complete(err, fs) {
if(err) throw err;
_fs = fs;
callback();
}
return new Filer.FileSystem({
name: name,
provider: _provider.provider,
flags: flags
}, complete);
if(addShim) {
global.indexedDB = require('fake-indexeddb');
}
function fs() {
if(!_fs) {
throw "TestUtil: call setup() before fs()";
}
return _fs;
var result = fn();
if(addShim) {
delete global.indexedDB;
}
function provider() {
if(!_provider) {
throw "TestUtil: call setup() before provider()";
}
return _provider;
return result;
}
function setup(callback) {
// In browser we support specifying the provider via the query string
// (e.g., ?filer-provider=IndexedDB). If not specified, we use
// the Memory provider by default.
var providerType = getProviderType();
var name = uniqueName();
switch(providerType.toLowerCase()) {
case 'indexeddb':
_provider = new IndexedDBTestProvider(name);
break;
case 'memory':
_provider = new MemoryTestProvider(name);
break;
case 'default':
default:
var BestProvider = findBestProvider();
_provider = new BestProvider(name);
break;
}
function shell(options) {
var _fs = fs();
return new _fs.Shell(options);
// Allow passing FS flags on query string
var flags = global.filerArgs && global.filerArgs.flags ?
global.filerArgs.flags : 'FORMAT';
// Create a file system and wait for it to get setup
_provider.init();
function complete(err, fs) {
if(err) throw err;
_fs = fs;
callback();
}
return new Filer.FileSystem({
name: name,
provider: _provider.provider,
flags: flags
}, complete);
}
function fs() {
if(!_fs) {
throw new Error('TestUtil: call setup() before fs()');
}
return _fs;
}
function provider() {
if(!_provider) {
throw new Error('TestUtil: call setup() before provider()');
}
return _provider;
}
function shell(options) {
var _fs = fs();
return new _fs.Shell(options);
}
function cleanup(callback) {
if(!_provider) {
return;
}
_provider.cleanup(function() {
_provider = null;
_fs = null;
callback();
});
}
function typedArrayEqual(a, b) {
if(!(a && b)) {
return false;
}
if(a.length !== b.length) {
return false;
}
function cleanup(callback) {
if(!_provider) {
return;
for(var i = 0; i < a.length; ++ i) {
if(a[i] !== b[i]) {
return false;
}
_provider.cleanup(function() {
_provider = null;
_fs = null;
callback();
}
return true;
}
/**
* Parse JSON with serialized Buffers
*/
const parseBJSON = json =>
JSON.parse(json, (key, value) =>
value && value.type === 'Buffer' ?
Buffer.from(value.data) :
value
);
function createMockFn(implementation = undefined) {
const calls = [];
const mockFn = function(...args) {
calls.push({
args,
});
}
function typedArrayEqual(a, b) {
if(!(a && b)) {
return false;
if (typeof implementation === 'function') {
return implementation(...args);
}
if(a.length !== b.length) {
return false;
}
for(var i = 0; i < a.length; ++ i) {
if(a[i] !== b[i]) {
return false;
}
}
return true;
}
module.exports = {
uniqueName: uniqueName,
setup: setup,
fs: fs,
shell: shell,
provider: provider,
providers: {
IndexedDB: IndexedDBTestProvider,
WebSQL: WebSQLTestProvider,
Memory: MemoryTestProvider
},
cleanup: cleanup,
typedArrayEqual: typedArrayEqual
};
Object.defineProperty(mockFn, 'calls', {
get() {
return calls;
}
});
return mockFn;
}
}(this));
module.exports = {
uniqueName: uniqueName,
setup: setup,
fs: fs,
shell: shell,
provider: provider,
providers: {
IndexedDB: IndexedDBTestProvider,
Memory: MemoryTestProvider
},
cleanup: cleanup,
typedArrayEqual: typedArrayEqual,
parseBJSON,
shimIndexedDB,
createMockFn
};

View File

@ -1,49 +0,0 @@
var Filer = require('../..');
var needsCleanup = [];
if(global.addEventListener) {
global.addEventListener('beforeunload', function() {
needsCleanup.forEach(function(f) { f(); });
});
}
function WebSQLTestProvider(name) {
var _done = false;
var that = this;
function cleanup(callback) {
callback = callback || function(){};
if(!that.provider || _done) {
return callback();
}
// Provider is there, but db was never touched
if(!that.provider.db) {
return callback();
}
var context = that.provider.getReadWriteContext();
context.clear(function() {
that.provider = null;
_done = true;
callback();
});
}
function init() {
if(that.provider) {
return;
}
that.provider = new Filer.FileSystem.providers.WebSQL(name);
needsCleanup.push(cleanup);
}
this.init = init;
this.cleanup = cleanup;
}
WebSQLTestProvider.isSupported = function() {
return Filer.FileSystem.providers.WebSQL.isSupported();
};
module.exports = WebSQLTestProvider;

View File

@ -1,8 +1,10 @@
var Filer = require('../..');
var expect = require('chai').expect;
'use strict';
describe("Filer.Errors", function() {
it("has expected errors", function() {
const Filer = require('../../src');
const expect = require('chai').expect;
describe('Filer.Errors', function() {
it('has expected errors', function() {
expect(Filer.Errors).to.exist;
// By ctor -- if you add some to src/errors.js, also add here
@ -135,7 +137,7 @@ describe("Filer.Errors", function() {
});
it('should include all expected properties by default', function() {
var err = new Filer.Errors.ENOENT();
const err = new Filer.Errors.ENOENT();
expect(err.name).to.equal('ENOENT');
expect(err.code).to.equal('ENOENT');
expect(err.errno).to.equal(34);
@ -143,7 +145,7 @@ describe("Filer.Errors", function() {
});
it('should include extra properties when provided', function() {
var err = new Filer.Errors.ENOENT('This is the message', '/this/is/the/path');
const err = new Filer.Errors.ENOENT('This is the message', '/this/is/the/path');
expect(err.name).to.equal('ENOENT');
expect(err.code).to.equal('ENOENT');
expect(err.errno).to.equal(34);
@ -152,29 +154,29 @@ describe("Filer.Errors", function() {
});
it('should include default message and path info when provided', function() {
var err = new Filer.Errors.ENOENT(null, '/this/is/the/path');
const err = new Filer.Errors.ENOENT(null, '/this/is/the/path');
expect(err.message).to.equal('no such file or directory');
expect(err.path).to.equal('/this/is/the/path');
});
it('should include just the message when no path provided', function() {
var err = new Filer.Errors.ENOENT();
const err = new Filer.Errors.ENOENT();
expect(err.message).to.equal('no such file or directory');
expect(err.path).not.to.exist;
});
it('should not include path in toString() when not provided', function() {
var err = new Filer.Errors.ENOENT('This is the message');
expect(err.toString()).to.equal("ENOENT: This is the message");
const err = new Filer.Errors.ENOENT('This is the message');
expect(err.toString()).to.equal('ENOENT: This is the message');
});
it('should include path in toString() when provided', function() {
var err = new Filer.Errors.ENOENT(null, '/this/is/the/path');
expect(err.toString()).to.equal("ENOENT: no such file or directory, '/this/is/the/path'");
const err = new Filer.Errors.ENOENT(null, '/this/is/the/path');
expect(err.toString()).to.equal('ENOENT: no such file or directory, \'/this/is/the/path\'');
});
it('should include message and path info when provided', function() {
var err = new Filer.Errors.ENOENT('This is the message', '/this/is/the/path');
const err = new Filer.Errors.ENOENT('This is the message', '/this/is/the/path');
expect(err.message).to.equal('This is the message');
expect(err.path).to.equal('/this/is/the/path');
});

Some files were not shown because too many files have changed in this diff Show More