Socket
Socket
Sign inDemoInstall

fs-jetpack

Package Overview
Dependencies
Maintainers
1
Versions
61
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

fs-jetpack - npm Package Compare versions

Comparing version 4.1.0 to 4.1.1

2

package.json
{
"name": "fs-jetpack",
"description": "Better file system API",
"version": "4.1.0",
"version": "4.1.1",
"author": "Jakub Szwacz <jakub@szwacz.com>",

@@ -6,0 +6,0 @@ "dependencies": {

@@ -1,14 +0,9 @@

fs-jetpack [![Build Status](https://travis-ci.com/szwacz/fs-jetpack.svg?branch=master)](https://travis-ci.com/szwacz/fs-jetpack) [![Build status](https://ci.appveyor.com/api/projects/status/er206e91fpuuqf58?svg=true)](https://ci.appveyor.com/project/szwacz/fs-jetpack) [![codecov](https://codecov.io/gh/szwacz/fs-jetpack/branch/master/graph/badge.svg)](https://codecov.io/gh/szwacz/fs-jetpack)
==========
# fs-jetpack [![Build Status](https://travis-ci.com/szwacz/fs-jetpack.svg?branch=master)](https://travis-ci.com/szwacz/fs-jetpack) [![Build status](https://ci.appveyor.com/api/projects/status/er206e91fpuuqf58?svg=true)](https://ci.appveyor.com/project/szwacz/fs-jetpack) [![codecov](https://codecov.io/gh/szwacz/fs-jetpack/branch/master/graph/badge.svg)](https://codecov.io/gh/szwacz/fs-jetpack)
Node's [fs library](http://nodejs.org/api/fs.html) is very low level and because of that often painful to use. *fs-jetpack* wants to fix that by giving you completely rethought, much more convenient API to work with file system.
_Fs-jetpack_ was brought to life out of frustration: "Why [node.js standard 'fs' library](http://nodejs.org/api/fs.html) has to be so tedious in use?. There are efforts to make mentioned API more pleasant ([fs-extra](https://github.com/jprichardson/node-fs-extra), [mkdirp](https://github.com/isaacs/node-mkdirp), [rimraf](https://github.com/isaacs/rimraf), etc.) but all of them just sprinkle something extra on top, not addressing the problem from the ground up. That's what _fs-jetpack_ did. Just started from scratch, and now has to offer completely redesigned, much more convenient API to work with file system.
Check out [EXAMPLES](EXAMPLES.md) to see few snippets what it can do.
# Table of Contents
[Installation](#installation)
[Sync & Async](#sync--async)
[Usage with TypeScript](#usage-with-typescript)
[Upgrading to New Version](#upgrading-to-new-version)
[Key Concepts](#key-concepts)
[Getting Started](#getting-started)

@@ -37,37 +32,95 @@ **API:**

## Installation
# Key Concepts
### Why not use more than one CWD?
You can create many fs-jetpack objects with different internal working directories (which are independent from `process.cwd()`) and work on directories in a little more object-oriented manner.
```js
const src = jetpack.cwd("path/to/source");
const dest = jetpack.cwd("/some/different/path/to/destination");
src.copy("foo.txt", dest.path("bar.txt"));
```
npm install fs-jetpack
### JSON is a first class citizen
You can write JavaScript object directly to disk and it will be transformed into JSON automatically.
```js
const obj = { greet: "Hello World!" };
jetpack.write("file.json", obj);
```
### Usage
```javascript
const jetpack = require('fs-jetpack');
Then you can get your object back just by telling `read` method that it's a JSON.
```js
const obj = jetpack.read("file.json", "json");
```
## Sync & Async
### Automatic handling of ENOENT errors
Everyone who has a lot to do with file system probably is sick of seeing error _"ENOENT, no such file or directory"_. Fs-jetpack tries to recover from this.
- For write/creation operations, if any of parent directories doesn't exist jetpack will just create them as well (like `mkdir -p` works).
- For read/inspect operations, if file or directory doesn't exist `undefined` is returned instead of throwing.
### Sync & async harmony
API has the same set of synchronous and asynchronous methods. All async methods are promise based (no callbacks).
Commonly used naming convention in Node world is reversed in this library (no 'method' and 'methodSync' naming). Asynchronous methods are those with 'Async' suffix, all methods without 'Async' in the name are synchronous. Reason behind this is that it gives very nice look to blocking API. And promise-based, non-blocking code is verbose anyway, so one more word is not much of a difference.
Commonly used naming convention in node.js world has been flipped in this API, so no `method()` (async) and `methodSync()` naming. Here the convention is `methodAsync()` and `method()` (sync). I know this looks wrong to you, but bear with me. Thanks to that, you always know how fs-jetpack method behaves, just by looking at the name: **If you don't see the word "Async", this method returns value immediately, if you do, promise is returned.** Standard node.js naming can't give you this clarity.
Also it's just convenient...
If you don't see the word "Async" in method name it always, across the whole API returns value immediately.
```js
// Synchronous call
const data = jetpack.read('file.txt');
console.log(data);
// Asynchronous call
const data = await jetpack.readAsync('file.txt');
console.log(data);
```
When you see "Async" that method returns promise which when resolved returns value.
## All API methods cooperate nicely with each other
Let's say you want to create folder structure...
```
.
|- greets
|- greet.txt
|- greet.json
|- greets-i18n
|- polish.txt
```
Peace of cake with jetpack!
```js
jetpack.readAsync('file.txt')
.then((data) => {
console.log(data);
});
jetpack
.dir("greets")
.file("greet.txt", { content: "Hello world!" })
.file("greet.json", { content: { greet: "Hello world!" } })
.cwd("..")
.dir("greets-i18n")
.file("polish.txt", { content: "Witaj świecie!" });
```
# Getting Started
## Installation
```
npm install fs-jetpack
```
Import to your code:
```javascript
const jetpack = require("fs-jetpack");
```
## Usage with TypeScript
Starting from v2.1.0 fs-jetpack is TypeScript compatible. But for backwards compatibility purposes all types and interfaces are reachable through special path `fs-jetpack/types`.
```typescript

@@ -84,3 +137,3 @@ // Import fs-jetpack into TypeScript code (the jetpack typings will be loaded as well).

This API is considered stable and all breaking changes to it are done as completely last resort. It also uses "better safe than sorry" approach to bumping major version number. So in 99.9% of cases you can upgrade to latest version with no worries, because all major version bumps are due to some edge case behaviour changes.
This API is considered stable and all breaking changes to it are done as completely last resort. It also uses "better safe than sorry" approach to bumping major version number. So in 99.9% of cases you can upgrade to latest version with no worries, because all major version bumps so far, were due to edge case behaviour changes.

@@ -90,2 +143,3 @@ # API

## append(path, data, [options])
asynchronous: **appendAsync(path, data, [options])**

@@ -99,11 +153,12 @@

`options` (optional) `Object` with possible fields:
* `mode` if the file doesn't exist yet, will be created with given mode. Value could be number (eg. `0o700`) or string (eg. `'700'`).
- `mode` if the file doesn't exist yet, will be created with given mode. Value could be number (eg. `0o700`) or string (eg. `'700'`).
**returns:**
Nothing.
## copy(from, to, [options])
asynchronous: **copyAsync(from, to, [options])**
asynchronous: **copyAsync(from, to, [options])**
Copies given file or directory (with everything inside).

@@ -114,7 +169,8 @@

`to` path to destination location, where the copy should be placed.
`options` (optional) additional options for customization. Is an `Object` with possible fields:
* `overwrite` (default: `false`) Whether to overwrite destination path when it already exists. Can be `Boolean` or `Function`. If `false`, an error will be thrown if it already exists. If `true`, the overwrite will be performed (for directories, this overwrite consists of a recursive merge - i.e. only files that already exist in the destination directory will be overwritten). If a function was provided, every time there is a file conflict while copying the function will be invoked with [inspect](#inspectpath-options) objects of both: source and destination file and overwrites the file only if `true` has been returned from the function (see example below). In async mode, the overwrite function can also return a promise, so you can perform multi step processes to determine if file should be overwritten or not (see example below).
* `matching` if defined will actually copy **only** items matching any of specified glob patterns and omit everything else ([all possible globs are described further in this readme](#matching-patterns)).
* `ignoreCase` (default `false`) whether or not case should be ignored when processing glob patterns passed through the `matching` option.
`options` (optional) additional options for customization. Is an `Object` with possible fields:
- `overwrite` (default: `false`) Whether to overwrite destination path when it already exists. Can be `Boolean` or `Function`. If `false`, an error will be thrown if it already exists. If `true`, the overwrite will be performed (for directories, this overwrite consists of a recursive merge - i.e. only files that already exist in the destination directory will be overwritten). If a function was provided, every time there is a file conflict while copying the function will be invoked with [inspect](#inspectpath-options) objects of both: source and destination file and overwrites the file only if `true` has been returned from the function (see example below). In async mode, the overwrite function can also return a promise, so you can perform multi step processes to determine if file should be overwritten or not (see example below).
- `matching` if defined will actually copy **only** items matching any of specified glob patterns and omit everything else ([all possible globs are described further in this readme](#matching-patterns)).
- `ignoreCase` (default `false`) whether or not case should be ignored when processing glob patterns passed through the `matching` option.
**returns:**

@@ -124,9 +180,10 @@ Nothing.

**examples:**
```javascript
// Copies a file (and replaces it if one already exists in 'foo' directory)
jetpack.copy('file.txt', 'foo/file.txt', { overwrite: true });
jetpack.copy("file.txt", "foo/file.txt", { overwrite: true });
// Copies files from folder foo_1 to foo_final, but overwrites in
// foo_final only files which are newer in foo_1.
jetpack.copy('foo_1', 'foo_final', {
jetpack.copy("foo_1", "foo_final", {
overwrite: (srcInspectData, destInspectData) => {

@@ -139,8 +196,7 @@ return srcInspectData.modifyTime > destInspectData.modifyTime;

// but overwrites only files containing "John Doe" string.
jetpack.copyAsync('foo_1', 'foo_final', {
jetpack.copyAsync("foo_1", "foo_final", {
overwrite: (srcInspectData, destInspectData) => {
return jetpack.readAsync(srcInspectData.absolutePath,)
.then((data) => {
return data.includes('John Doe');
});
return jetpack.readAsync(srcInspectData.absolutePath).then(data => {
return data.includes("John Doe");
});
}

@@ -150,5 +206,5 @@ });

// Copies only '.md' files from 'foo' (and subdirectories of 'foo') to 'bar'.
jetpack.copy('foo', 'bar', { matching: '*.md' });
jetpack.copy("foo", "bar", { matching: "*.md" });
// Copies only '.md' and '.txt' files from 'foo' (and subdirectories of 'foo') to 'bar'.
jetpack.copy('foo', 'bar', { matching: ['*.md', '*.txt'] });
jetpack.copy("foo", "bar", { matching: ["*.md", "*.txt"] });

@@ -158,6 +214,6 @@ // You can filter previous matches by defining negated pattern further in the order:

// but will skip file '!top-secret.md'.
jetpack.copy('foo', 'bar', { matching: ['*.md', '!top-secret.md'] });
jetpack.copy("foo", "bar", { matching: ["*.md", "!top-secret.md"] });
// Copies only '.md' files from 'foo' (and subdirectories of 'foo') to 'bar'
// but will skip all files in 'foo/top-secret' directory.
jetpack.copy('foo', 'bar', { matching: ['*.md', '!top-secret/**/*'] });
jetpack.copy("foo", "bar", { matching: ["*.md", "!top-secret/**/*"] });

@@ -167,8 +223,7 @@ // All patterns are anchored to directory you want to copy, not to CWD.

// to 'copied-dir2/images'
jetpack.copy('dir1/dir2', 'copied-dir2', {
matching: 'images/**'
jetpack.copy("dir1/dir2", "copied-dir2", {
matching: "images/**"
});
```
## createReadStream(path, [options])

@@ -178,3 +233,2 @@

## createWriteStream(path, [options])

@@ -184,5 +238,4 @@

## cwd([path...])
## cwd([path...])
Returns Current Working Directory (CWD) for this instance of jetpack, or creates new jetpack object with given path as its internal CWD.

@@ -200,2 +253,3 @@

**examples:**
```javascript

@@ -208,20 +262,20 @@ // Let's assume that process.cwd() outputs...

// Now let's create new CWD context...
const jetParent = jetpack.cwd('..');
const jetParent = jetpack.cwd("..");
console.log(jetParent.cwd()); // '/one/two'
// ...and use this new context.
jetParent.dir('four'); // we just created directory '/one/two/four'
jetParent.dir("four"); // we just created directory '/one/two/four'
// One CWD context can be used to create next CWD context.
const jetParentParent = jetParent.cwd('..');
const jetParentParent = jetParent.cwd("..");
console.log(jetParentParent.cwd()); // '/one'
// When many parameters specified they are treated as parts of path to resolve
const sillyCwd = jetpack.cwd('a', 'b', 'c');
const sillyCwd = jetpack.cwd("a", "b", "c");
console.log(sillyCwd.cwd()); // '/one/two/three/a/b/c'
```
## dir(path, [criteria])
asynchronous: **dirAsync(path, [criteria])**
asynchronous: **dirAsync(path, [criteria])**
Ensures that directory on given path exists and meets given criteria. If any criterium is not met it will be after this call. If any parent directory in `path` doesn't exist it will be created (like `mkdir -p`).

@@ -234,15 +288,17 @@

`criteria` (optional) criteria to be met by the directory. Is an `Object` with possible fields:
* `empty` (default: `false`) whether directory should be empty (no other files or directories inside). If set to `true` and directory contains any files or subdirectories all of them will be deleted.
* `mode` ensures directory has specified mode. If not set and directory already exists, current mode will be preserved. Value could be number (eg. `0o700`) or string (eg. `'700'`).
- `empty` (default: `false`) whether directory should be empty (no other files or directories inside). If set to `true` and directory contains any files or subdirectories all of them will be deleted.
- `mode` ensures directory has specified mode. If not set and directory already exists, current mode will be preserved. Value could be number (eg. `0o700`) or string (eg. `'700'`).
**returns:**
New CWD context with directory specified in `path` as CWD (see docs of `cwd()` method for explanation).
New CWD context with directory specified in `path` as CWD (see docs of `cwd()` method for explanation).
**examples:**
```javascript
// Creates directory if doesn't exist
jetpack.dir('new-dir');
jetpack.dir("new-dir");
// Makes sure directory mode is 0700 and that it's empty
jetpack.dir('empty-dir', { empty: true, mode: '700' });
jetpack.dir("empty-dir", { empty: true, mode: "700" });

@@ -252,22 +308,23 @@ // Because dir returns new CWD context pointing to just

jetpack
.dir('main-dir') // creates 'main-dir'
.dir('sub-dir'); // creates 'main-dir/sub-dir'
.dir("main-dir") // creates 'main-dir'
.dir("sub-dir"); // creates 'main-dir/sub-dir'
```
## exists(path)
asynchronous: **existsAsync(path)**
asynchronous: **existsAsync(path)**
Checks whether something exists on given `path`. This method returns values more specific than `true/false` to protect from errors like "I was expecting directory, but it was a file".
**returns:**
* `false` if path doesn't exist.
* `"dir"` if path is a directory.
* `"file"` if path is a file.
* `"other"` if none of the above.
**returns:**
- `false` if path doesn't exist.
- `"dir"` if path is a directory.
- `"file"` if path is a file.
- `"other"` if none of the above.
## file(path, [criteria])
asynchronous: **fileAsync(path, [criteria])**
asynchronous: **fileAsync(path, [criteria])**
Ensures that file exists and meets given criteria. If any criterium is not met it will be after this call. If any parent directory in `path` doesn't exist it will be created (like `mkdir -p`).

@@ -278,6 +335,7 @@

`criteria` (optional) criteria to be met by the file. Is an `Object` with possible fields:
* `content` sets file content. Can be `String`, `Buffer`, `Object` or `Array`. If `Object` or `Array` given to this parameter data will be written as JSON.
* `jsonIndent` (defaults to 2) if writing JSON data this tells how many spaces should one indentation have.
* `mode` ensures file has specified mode. If not set and file already exists, current mode will be preserved. Value could be number (eg. `0o700`) or string (eg. `'700'`).
- `content` sets file content. Can be `String`, `Buffer`, `Object` or `Array`. If `Object` or `Array` given to this parameter data will be written as JSON.
- `jsonIndent` (defaults to 2) if writing JSON data this tells how many spaces should one indentation have.
- `mode` ensures file has specified mode. If not set and file already exists, current mode will be preserved. Value could be number (eg. `0o700`) or string (eg. `'700'`).
**returns:**

@@ -287,12 +345,13 @@ Jetpack object you called this method on (self).

**examples:**
```javascript
// Creates file if doesn't exist
jetpack.file('something.txt');
jetpack.file("something.txt");
// Creates file with mode '777' and content 'Hello World!'
jetpack.file('hello.txt', { mode: '777', content: 'Hello World!' });
jetpack.file("hello.txt", { mode: "777", content: "Hello World!" });
```
## find([path], searchOptions)
## find([path], searchOptions)
asynchronous: **findAsync([path], searchOptions)**

@@ -305,8 +364,9 @@

`searchOptions` is an `Object` with possible fields:
* `matching` glob patterns of files you want to find ([all possible globs are described further in this readme](#matching-patterns)).
* `files` (default `true`) whether or not should search for files.
* `directories` (default `false`) whether or not should search for directories.
* `recursive` (default `true`) whether the whole directory tree should be searched recursively, or only one-level of given directory (excluding it's subdirectories).
* `ignoreCase` (`false` otherwise) whether or not case should be ignored when processing glob patterns passed through the `matching` option.
- `matching` glob patterns of files you want to find ([all possible globs are described further in this readme](#matching-patterns)).
- `files` (default `true`) whether or not should search for files.
- `directories` (default `false`) whether or not should search for directories.
- `recursive` (default `true`) whether the whole directory tree should be searched recursively, or only one-level of given directory (excluding it's subdirectories).
- `ignoreCase` (`false` otherwise) whether or not case should be ignored when processing glob patterns passed through the `matching` option.
**returns:**

@@ -316,31 +376,41 @@ `Array` of found paths.

**examples:**
```javascript
// Finds all files which has 2015 in the name
jetpack.find('my-work', { matching: '*2015*' });
jetpack.find("my-work", { matching: "*2015*" });
// Finds all '.txt' files inside 'foo/bar' directory and its subdirectories
jetpack.find('foo', { matching: 'bar/**/*.txt' });
// Finds all '.txt' files inside 'foo/bar' directory WITHOUT subdirectories
jetpack.find('foo', { matching: 'bar/*.txt' });
jetpack.find("foo", { matching: "bar/**/*.txt" });
// Finds all '.txt' files inside 'foo/bar' directory WITHOUT subdirectories
jetpack.find("foo", { matching: "bar/*.txt" });
// Finds all '.js' files inside 'my-project' but excluding those in 'vendor' subtree.
jetpack.find('my-project', { matching: ['*.js', '!vendor/**/*'] });
jetpack.find("my-project", { matching: ["*.js", "!vendor/**/*"] });
// Looks for all directories named 'foo' (and will omit all files named 'foo').
jetpack.find('my-work', { matching: ['foo'], files: false, directories: true });
jetpack.find("my-work", { matching: ["foo"], files: false, directories: true });
// Finds all '.txt' files inside 'foo' directory WITHOUT subdirectories
jetpack.find('foo', { matching: './*.txt' });
// Finds all '.txt' files inside 'foo' directory WITHOUT subdirectories
jetpack.find("foo", { matching: "./*.txt" });
// This line does the same as the above, but has better performance
// (skips looking in subdirectories)
jetpack.find('foo', { matching: '*.txt', recursive: false });
jetpack.find("foo", { matching: "*.txt", recursive: false });
// Path parameter might be omitted and CWD is used as path in that case.
const myStuffDir = jetpack.cwd('my-stuff');
myStuffDir.find({ matching: ['*.md'] });
const myStuffDir = jetpack.cwd("my-stuff");
myStuffDir.find({ matching: ["*.md"] });
// You can chain find() with different jetpack methods for more power.
// For example lets delete all `.tmp` files inside `foo` directory
jetpack
.find("foo", {
matching: "*.tmp"
})
.forEach(jetpack.remove);
```
## inspect(path, [options])
asynchronous: **inspectAsync(path, [options])**
asynchronous: **inspectAsync(path, [options])**
Inspects given path (replacement for `fs.stat`). Returned object by default contains only very basic, not platform-dependent properties (so you have something e.g. your unit tests can rely on), you can enable more properties through options object.

@@ -351,11 +421,13 @@

`options` (optional). Possible values:
* `checksum` if specified will return checksum of inspected file. Possible values are strings `'md5'`, `'sha1'`, `'sha256'` or `'sha512'`. If given path is directory this field is ignored.
* `mode` (default `false`) if set to `true` will add file mode (unix file permissions) value.
* `times` (default `false`) if set to `true` will add atime, mtime and ctime fields (here called `accessTime`, `modifyTime` and `changeTime`).
* `absolutePath` (default `false`) if set to `true` will add absolute path to this resource.
* `symlinks` (default `'report'`) if a given path is a symlink by default `inspect` will report that symlink (not follow it). You can flip this behaviour by setting this option to `'follow'`.
- `checksum` if specified will return checksum of inspected file. Possible values are strings `'md5'`, `'sha1'`, `'sha256'` or `'sha512'`. If given path is directory this field is ignored.
- `mode` (default `false`) if set to `true` will add file mode (unix file permissions) value.
- `times` (default `false`) if set to `true` will add atime, mtime and ctime fields (here called `accessTime`, `modifyTime` and `changeTime`).
- `absolutePath` (default `false`) if set to `true` will add absolute path to this resource.
- `symlinks` (default `'report'`) if a given path is a symlink by default `inspect` will report that symlink (not follow it). You can flip this behaviour by setting this option to `'follow'`.
**returns:**
`undefined` if given path doens't exist.
Otherwise `Object` of structure:
```javascript

@@ -377,6 +449,6 @@ {

## inspectTree(path, [options])
asynchronous: **inspectTreeAsync(path, [options])**
asynchronous: **inspectTreeAsync(path, [options])**
Calls [inspect](#inspectpath-options) recursively on given path so it creates tree of all directories and sub-directories inside it.

@@ -387,10 +459,12 @@

`options` (optional). Possible values:
* `checksum` if specified will also calculate checksum of every item in the tree. Possible values are strings `'md5'`, `'sha1'`, `'sha256'` or `'sha512'`. Checksums for directories are calculated as checksum of all children' checksums plus their filenames (see example below).
* `times` (default `false`) if set to `true` will add atime, mtime and ctime fields (here called `accessTime`, `modifyTime` and `changeTime`) to each tree node.
* `relativePath` if set to `true` every tree node will have relative path anchored to root inspected folder.
* `symlinks` (default `'report'`) if a given path is a symlink by default `inspectTree` will report that symlink (not follow it). You can flip this behaviour by setting this option to `'follow'`.
- `checksum` if specified will also calculate checksum of every item in the tree. Possible values are strings `'md5'`, `'sha1'`, `'sha256'` or `'sha512'`. Checksums for directories are calculated as checksum of all children' checksums plus their filenames (see example below).
- `times` (default `false`) if set to `true` will add atime, mtime and ctime fields (here called `accessTime`, `modifyTime` and `changeTime`) to each tree node.
- `relativePath` if set to `true` every tree node will have relative path anchored to root inspected folder.
- `symlinks` (default `'report'`) if a given path is a symlink by default `inspectTree` will report that symlink (not follow it). You can flip this behaviour by setting this option to `'follow'`.
**returns:**
`undefined` if given path doesn't exist.
Otherwise tree of inspect objects like:
```javascript

@@ -424,6 +498,6 @@ {

## list([path])
asynchronous: **listAsync(path)**
asynchronous: **listAsync(path)**
Lists the contents of directory. Equivalent of `fs.readdir`.

@@ -437,6 +511,6 @@

## move(from, to, [options])
asynchronous: **moveAsync(from, to, [options])**
asynchronous: **moveAsync(from, to, [options])**
Moves given path to new location.

@@ -447,10 +521,11 @@

`to` path where the thing should be moved.
`options` (optional) additional options for customization. Is an `Object` with possible fields:
* `overwrite` (default: `false`) Whether to overwrite destination path when it already exists. If `true`, the overwrite will be performed.
`options` (optional) additional options for customization. Is an `Object` with possible fields:
- `overwrite` (default: `false`) Whether to overwrite destination path when it already exists. If `true`, the overwrite will be performed.
**returns:**
Nothing.
## path(parts...)
## path(parts...)
Returns path resolved to internal CWD of this jetpack object.

@@ -465,13 +540,14 @@

**examples:**
```javascript
jetpack.cwd(); // if it returns '/one/two'
jetpack.path(); // this will return the same '/one/two'
jetpack.path('three'); // this will return '/one/two/three'
jetpack.path('..', 'four'); // this will return '/one/four'
jetpack.path("three"); // this will return '/one/two/three'
jetpack.path("..", "four"); // this will return '/one/four'
```
## read(path, [returnAs])
asynchronous: **readAsync(path, [returnAs])**
asynchronous: **readAsync(path, [returnAs])**
Reads content of file.

@@ -482,14 +558,15 @@

`returnAs` (optional) how the content of file should be returned. Is a string with possible values:
* `'utf8'` (default) content will be returned as UTF-8 String.
* `'buffer'` content will be returned as a Buffer.
* `'json'` content will be returned as parsed JSON object.
* `'jsonWithDates'` content will be returned as parsed JSON object, and date strings in [ISO format](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString) will be automatically turned into Date objects.
- `'utf8'` (default) content will be returned as UTF-8 String.
- `'buffer'` content will be returned as a Buffer.
- `'json'` content will be returned as parsed JSON object.
- `'jsonWithDates'` content will be returned as parsed JSON object, and date strings in [ISO format](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString) will be automatically turned into Date objects.
**returns:**
File content in specified format, or `undefined` if file doesn't exist.
## remove([path])
asynchronous: **removeAsync([path])**
asynchronous: **removeAsync([path])**
Deletes given path, no matter what it is (file, directory or non-empty directory). If path already doesn't exist terminates gracefully without throwing, so you can use it as 'ensure path doesn't exist'.

@@ -504,19 +581,20 @@

**examples:**
```javascript
// Deletes file
jetpack.remove('my_work/notes.txt');
jetpack.remove("my_work/notes.txt");
// Deletes directory "important_stuff" and everything inside
jetpack.remove('my_work/important_stuff');
jetpack.remove("my_work/important_stuff");
// Remove can be called with no parameters and will default to CWD then.
// In this example folder 'my_work' will cease to exist.
const myStuffDir = jetpack.cwd('my_stuff');
const myStuffDir = jetpack.cwd("my_stuff");
myStuffDir.remove();
```
## rename(path, newName, [options])
asynchronous: **renameAsync(path, newName, [options])**
asynchronous: **renameAsync(path, newName, [options])**
Renames given file or directory.

@@ -527,5 +605,6 @@

`newName` new name for this thing (not full path, just a name).
`options` (optional) additional options for customization. Is an `Object` with possible fields:
* `overwrite` (default: `false`) Whether to overwrite destination path when it already exists. If `true`, the overwrite will be performed.
`options` (optional) additional options for customization. Is an `Object` with possible fields:
- `overwrite` (default: `false`) Whether to overwrite destination path when it already exists. If `true`, the overwrite will be performed.
**returns:**

@@ -535,10 +614,12 @@ Nothing.

**examples:**
```javascript
// The file "my_work/important.md" will be renamed to "my_work/very_important.md"
jetpack.rename('my_work/important.txt', 'very_important.md');
jetpack.rename("my_work/important.txt", "very_important.md");
```
## symlink(symlinkValue, path)
asynchronous: **symlinkAsync(symlinkValue, path)**
asynchronous: **symlinkAsync(symlinkValue, path)**
Creates symbolic link.

@@ -548,3 +629,3 @@

`symlinkValue` path where symbolic link should point.
`path` path where symbolic link should be put.
`path` path where symbolic link should be put.

@@ -555,4 +636,5 @@ **returns:**

## tmpDir([options])
asynchronous: **tmpDirAsync([options])**
asynchronous: **tmpDirAsync([options])**
Creates temporary directory with random, unique name.

@@ -562,26 +644,37 @@

`options` (optional) `Object` with possible fields:
* `prefix` prefix to be added to created random directory name. Defaults to none.
* `basePath` the path where temporary directory should be created. Defaults to [https://nodejs.org/api/os.html#os_os_tmpdir](os.tmpdir).
- `prefix` prefix to be added to created random directory name. Defaults to none.
- `basePath` the path where temporary directory should be created. Defaults to [https://nodejs.org/api/os.html#os_os_tmpdir](os.tmpdir).
**returns:**
New CWD context with temporary directory specified in `path` as CWD (see docs of `cwd()` method for explanation).
New CWD context with temporary directory specified in `path` as CWD (see docs of `cwd()` method for explanation).
**examples:**
```javascript
// Creates temporary directory, e.g. /tmp/90ed0f0f4a0ba3b1433c5b51ad8fc76b
jetpack.tempDir()
// You can interact with this directory by returned CWD context.
const dirContext = jetpack.tmpDir();
// Creates temporary directory with a prefix, e.g. /tmp/foo_90ed0f0f4a0ba3b1433c5b51ad8fc76b
jetpack.tempDir({ prefix: "foo_" })
jetpack.tmpDir({ prefix: "foo_" });
// Creates temporary directory on given path, e.g. /some/other/path/90ed0f0f4a0ba3b1433c5b51ad8fc76b
jetpack.tempDir({ basePath: "/some/other/path" })
jetpack.tmpDir({ basePath: "/some/other/path" });
// Creates temporary directory on jetpack.cwd() path
jetpack.tempDir({ basePath: "." })
jetpack.tmpDir({ basePath: "." });
// Create temporary directory and write a file to that directory
jetpack.tempDir().write("foo.txt", "Hello world!");
// The method returns new jetpack context, so you can easily clean your
// temp files after you're done.
const dir = jetpack.tmpDir();
dir.write("foo.txt", data);
// ...and when you're done using the dir...
dir.remove();
```
## write(path, data, [options])
asynchronous: **writeAsync(path, data, [options])**
asynchronous: **writeAsync(path, data, [options])**
Writes data to file. If any parent directory in `path` doesn't exist it will be created (like `mkdir -p`).

@@ -593,6 +686,7 @@

`options` (optional) `Object` with possible fields:
* `mode` file will be created with given mode. Value could be number (eg. `0o700`) or string (eg. `'700'`).
* `atomic` (default `false`) if set to `true` the file will be written using strategy which is much more resistant to data loss. The trick is very simple, [read this to get the concept](http://stackoverflow.com/questions/17047994/transactionally-writing-files-in-node-js).
* `jsonIndent` (defaults to 2) if writing JSON data this tells how many spaces should one indentation have.
- `mode` file will be created with given mode. Value could be number (eg. `0o700`) or string (eg. `'700'`).
- `atomic` (default `false`) if set to `true` the file will be written using strategy which is much more resistant to data loss. The trick is very simple, [read this to get the concept](http://stackoverflow.com/questions/17047994/transactionally-writing-files-in-node-js).
- `jsonIndent` (defaults to 2) if writing JSON data this tells how many spaces should one indentation have.
**returns:**

@@ -616,6 +710,2 @@ Nothing.

*(explanation borrowed from [glob](https://github.com/isaacs/node-glob) which is using [the same matching library](https://github.com/isaacs/minimatch) as this project)*
# License
Released under the MIT license.
_(explanation borrowed from [glob](https://github.com/isaacs/node-glob) which is using [the same matching library](https://github.com/isaacs/minimatch) as this project)_

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc