memfs

2018-10-11 admin

memfs是什么

什么是memfs,In-memory file-system with Node's fs API.

memfs使用教程帮助文档

memfs 2.0

In-memory file-system with Node’s fs API.

  • 100% of Node’s fs API implemented, see API Status
  • Stores files in memory, in Buffers
  • Throws same* errors as Node.js
  • Has concept of i-nodes
  • Implements hard links
  • Implements soft links (aka symlinks, symbolic links)
  • More testing coming soon*
  • Permissions may* be implemented in the future
  • Can be used in browser, see memfs-webpack

Install

npm install --save memfs

Usage

import {fs} from 'memfs';

fs.writeFileSync('/hello.txt', 'World!');
fs.readFileSync('/hello.txt', 'utf8'); // World!

Create a file system from a plain JSON:

import {fs, vol} from 'memfs';

const json = {
    './README.md': '1',
    './src/index.js': '2',
    './node_modules/debug/index.js': '3',
};
vol.fromJSON(json, '/app');

fs.readFileSync('/app/README.md', 'utf8'); // 1
vol.readFileSync('/app/src/index.js', 'utf8'); // 2

Export to JSON:

vol.writeFileSync('/script.sh', 'sudo rm -rf *');
vol.toJSON(); // {"/script.sh": "sudo rm -rf *"}

Use it for testing:

vol.writeFileSync('/foo', 'bar');
expect(vol.toJSON()).toEqual({"/foo": "bar"});

Create as many filesystem volumes as you need:

import {Volume} from 'memfs';

const vol = Volume.fromJSON({'/foo': 'bar'});
vol.readFileSync('/foo'); // bar

const vol2 = Volume.fromJSON({'/foo': 'bar 2'});
vol2.readFileSync('/foo'); // bar 2

Use memfs together with unionfs to create one filesystem from your in-memory volumes and the real disk filesystem:

import * as fs from 'fs';
import {ufs} from 'unionfs';

ufs
    .use(fs)
    .use(vol);

ufs.readFileSync('/foo'); // bar

Use fs-monkey to monkey-patch Node’s require function:

import {patchRequire} from 'fs-monkey';

vol.writeFileSync('/index.js', 'console.log("hi world")');
patchRequire(vol);
require('/index'); // hi world

Docs

See also

  • spyfs - spies on filesystem actions
  • unionfs - creates a union of multiple filesystem volumes
  • linkfs - redirects filesystem paths
  • fs-monkey - monkey-patches Node’s fs module and require function
  • libfs - real filesystem (that executes UNIX system calls) implemented in JavaScript

Dependencies

This package depends on the following Node modules: buffer, events, streams, path.

It also uses process and setImmediate globals, but mocks them, if not available.

License

Unlicense - public domain.

本站文章除注明转载外,均为本站原创或编译。欢迎任何形式的转载,但请务必注明出处。

转载请注明:文章转载自 JavaScript中文网 [https://www.javascriptcn.com]

本文地址:https://www.javascriptcn.com/read-42424.html

文章标题:memfs

回到顶部