• Stars
    star
    146
  • Rank 252,769 (Top 5 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 4 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Write files atomically and reliably.

Atomically

Read and write files atomically and reliably.

Features

  • Overview:
    • This library is a rewrite of write-file-atomic, with some important enhancements on top, you can largely use this as a drop-in replacement.
    • This library is written in TypeScript, so types aren't an afterthought but come with library.
    • This library is slightly faster than write-file-atomic, and it can be 10x faster, while being essentially just as safe, by using the fsyncWait option.
    • This library has 0 third-party dependencies, so there's less code to vet and the entire thing is roughly 20% smaller than write-file-atomic.
    • This library tries harder to write files on disk than write-file-atomic does, by default retrying some failed operations and handling some more errors.
  • Reliability:
    • Reads are retried, when appropriate, until they succeed or the timeout is reached.
    • Writes are atomic, meaning that first a temporary file containing the new content is written, then this file is renamed to the final path, this way it's impossible to get a corrupt/partially-written file.
    • Writes happening to the same path are queued, ensuring they don't interfere with each other.
    • Temporary files can be configured to not be purged from disk if the write operation fails, which is useful for when keeping the temporary file is better than just losing data.
    • Any needed missing parent folder will be created automatically.
    • Symlinks are resolved automatically.
    • ENOSYS errors on chmod/chown operations are ignored.
    • EINVAL/EPERM errors on chmod/chown operations, in POSIX systems where the user is not root, are ignored.
    • EMFILE/ENFILE/EAGAIN/EBUSY/EACCESS/EACCES/EACCS/EPERM errors happening during necessary operations are caught and the operations are retried until they succeed or the timeout is reached.
    • ENAMETOOLONG errors, both appening because of the final path or the temporary path, are attempted to be worked around by smartly truncating paths.
  • Temporary files:
    • By default they are purged automatically once the write operation is completed or if the process exits (cleanly or not).
    • By default they are created by appending a .tmp-[timestamp][randomness] suffix to destination paths:
      • The tmp- part gives users a hint about the nature of these files, if they happen to see them.
      • The [timestamp] part consists of the 10 least significant digits of a milliseconds-precise timestamp, making it likely that if more than one of these files are kept on disk the user will see them in chronological order.
      • The [randomness] part consists of 6 random hex characters.
      • If by any chance a collision is found then another suffix is generated.
  • Custom options:
    • chown: it allows you to specify custom group and user ids:
      • by default the old file's ids are copied over.
      • if custom ids are provided they will be used.
      • if false the default ids are used.
    • encoding: it allows you to specify the encoding of the file content:
      • by default when reading no encoding is specified and a raw buffer is returned.
      • by default when writing utf8 is used when.
    • fsync: it allows you to control whether the fsync syscall is triggered right after writing the file or not:
      • by default the syscall is triggered immediately after writing the file, increasing the chances that the file will actually be written to disk in case of imminent catastrophic failures, like power outages.
      • if false the syscall won't be triggered.
    • fsyncWait: it allows you to control whether the triggered fsync is waited or not:
      • by default the syscall is waited.
      • if false the syscall will still be triggered but not be waited.
        • this increases performance 10x in some cases, and at the end of the day often there's no plan B if fsync fails anyway.
    • mode: it allows you to specify the mode for the file:
      • by default the old file's mode is copied over.
      • if false then 0o666 is used.
    • schedule: it's a function that returns a promise that resolves to a disposer function, basically it allows you to provide some custom queueing logic for the writing operation, allowing you to perhaps wire atomically with your app's main filesystem job scheduler:
      • even when a custom schedule function is provided write operations will still be queued internally by the library too.
    • timeout: it allows you to specify the amount of maximum milliseconds within which the library will retry some failed operations:
      • when writing asynchronously by default it will keep retrying for 7500 milliseconds.
      • when writing synchronously by default it will keep retrying for 1000 milliseconds.
      • if 0 or -1 no failed operations will be retried.
      • if another number is provided that will be the timeout interval.
    • tmpCreate: it's a function that will be used to create the custom temporary file path in place of the default one:
      • even when a custom function is provided the final temporary path will still be truncated if the library thinks that it may lead to ENAMETOOLONG errors.
      • paths by default are truncated in a way that preserves an eventual existing leading dot and trailing extension.
    • tmpCreated: it's a function that will be called with the newly created temporary file path.
    • tmpPurge: it allows you to control whether the temporary file will be purged from the filesystem or not if the write fails:
      • by default it will be purged.
      • if false it will be kept on disk.

Install

npm install --save atomically

Usage

This is the shape of the optional options object:

type Disposer = () => void;

type ReadOptions = string | {
  encoding?: string | null,
  mode?: string | number | false,
  timeout?: number
};

type WriteOptions = string | {
  chown?: { gid: number, uid: number } | false,
  encoding?: string | null,
  fsync?: boolean,
  fsyncWait?: boolean,
  mode?: string | number | false,
  schedule?: ( filePath: string ) => Promise<Disposer>,
  timeout?: number,
  tmpCreate?: ( filePath: string ) => string,
  tmpCreated?: ( filePath: string ) => any,
  tmpPurge?: boolean
};

This is the shape of the provided functions:

function readFile ( filePath: string, options?: ReadOptions ): Promise<Buffer | string>;
function readFileSync ( filePath: string, options?: ReadOptions ): Buffer | string;
function writeFile ( filePath: string, data: Buffer | string | undefined, options?: WriteOptions ): Promise<void>;
function writeFileSync ( filePath: string, data: Buffer | string | undefined, options?: WriteOptions ): void;

This is how to use the library:

import {readFile, readFileSync, writeFile, writeFileSync} from 'atomically';

// Asynchronous read with default option
const buffer = await readFile ( '/foo.txt' );

// Synchronous read assuming the encoding is "utf8"
const string = readFileSync ( '/foo.txt', 'utf8' );

// Asynchronous write with default options
await writeFile ( '/foo.txt', 'my_data' );

// Asynchronous write that doesn't prod the old file for a stat object at all
await writeFile ( '/foo.txt', 'my_data', { chown: false, mode: false } );

// 10x faster asynchronous write that's less resilient against imminent catastrophies
await writeFile ( '/foo.txt', 'my_data', { fsync: false } );

// 10x faster asynchronous write that's essentially still as resilient against imminent catastrophies
await writeFile ( '/foo.txt', 'my_data', { fsyncWait: false } );

// Asynchronous write with a custom schedule function
await writeFile ( '/foo.txt', 'my_data', {
  schedule: filePath => {
    return new Promise ( resolve => { // When this returned promise will resolve the write operation will begin
      MyScheduler.schedule ( filePath, () => { // Hypothetical scheduler function that will eventually tell us to go on with this write operation
        const disposer = () => {}; // Hypothetical function that contains eventual clean-up logic, it will be called after the write operation has been completed (successfully or not)
        resolve ( disposer ); // Resolving the promise with a disposer, beginning the write operation
      })
    });
  }
});

// Synchronous write with default options
writeFileSync ( '/foo.txt', 'my_data' );

License

MIT © Fabio Spampinato

More Repositories

1

cash

An absurdly small jQuery alternative for modern browsers.
JavaScript
6,506
star
2

cliflix

Watch anything instantaneously, just write its name.
TypeScript
1,492
star
3

vscode-todo-plus

Manage todo lists with ease. Powerful, easy to use and customizable.
TypeScript
843
star
4

autogit

Define commands, using plugins, to execute across all your repositories.
TypeScript
471
star
5

phoenix

My Phoenix setup. Powerful, easy to customize, tuned for web development, adds a space switcher.
JavaScript
397
star
6

bump

Bump updates the project's version, updates/creates the changelog, makes the bump commit, tags the bump commit and makes the release to GitHub. Opinionated but configurable.
TypeScript
393
star
7

noty

Autosaving sticky note with support for multiple notes without needing multiple windows.
TypeScript
337
star
8

store

A beautifully-simple framework-agnostic modern state management library.
TypeScript
227
star
9

tiny-bin

A library for building tiny and beautiful command line apps.
TypeScript
175
star
10

template

A super-simple way to create new projects based on templates.
TypeScript
131
star
11

flimsy

A single-file <1kb min+gzip simplified implementation of the reactive core of Solid, optimized for clean code.
TypeScript
130
star
12

vscode-highlight

Advanced text highlighter based on regexes. Useful for todos, annotations etc.
TypeScript
126
star
13

vscode-terminals

An extension for setting-up multiple terminals at once, or just running some commands.
TypeScript
110
star
14

shosho

A modern and powerful shortcuts management library.
TypeScript
87
star
15

picorpc

A tiny RPC library and spec, inspired by JSON-RPC 2.0 and tRPC.
TypeScript
84
star
16

overstated

React state management library that's delightful to use, without sacrificing performance or scalability.
TypeScript
82
star
17

vscode-monokai-night

A complete, dark and minimalistic Monokai-inspired theme.
HTML
74
star
18

vscode-open-in-github

Open the current project or file in github.com.
TypeScript
72
star
19

enex-dump

Dump the content of .enex files, preserving attachements, some metadata and optionally converting notes to Markdown.
JavaScript
71
star
20

shortcuts

Super performant and feature rich shortcuts management library.
TypeScript
66
star
21

watcher

The file system watcher that strives for perfection, with no native dependencies and optional rename detection support.
JavaScript
65
star
22

vscode-projects-plus

An extension for managing projects. Feature rich, customizable, automatically finds your projects.
TypeScript
64
star
23

svelto

Modular front end framework for modern browsers, with battery included: 100+ widgets and tools.
JavaScript
60
star
24

icon-font-buildr

Build custom icon fonts, it supports remote and local icons sources.
TypeScript
51
star
25

pastebin-monitor

A simple Pastebin monitor which looks for interesting things and saves them to disk.
Python
50
star
26

vscode-commands

Trigger arbitrary commands from the statusbar. Supports passing arguments!
TypeScript
50
star
27

monorepo

The homepage for all my repositories.
49
star
28

rssa

RSS-Anything, get updates about anything you can reach with an url. Like RSS, but for anything.
TypeScript
49
star
29

proxy-watcher

A library that recursively watches an object for mutations via Proxies and tells you which paths changed.
JavaScript
46
star
30

banal

On-demand bundle analyzer, powered by esbuild.
HTML
42
star
31

template-vscode-extension

A template for starting a new vscode extension quickly.
TypeScript
37
star
32

khroma

A collection of functions for manipulating CSS colors, inspired by SASS.
JavaScript
36
star
33

lande

A tiny neural network for natural language detection.
TypeScript
33
star
34

vscode-projects-plus-todo-plus

Bird's-eye view over your projects, view all your todo files aggregated into one.
TypeScript
27
star
35

awesome-autogit

Curated list of resources for autogit.
27
star
36

vscode-diff

Diff 2 opened files with ease. Because running `code --diff path1 path2` is too slow.
TypeScript
26
star
37

termux-env

My super-quick-to-setup Termux environment.
Lua
26
star
38

zeptomatch

An absurdly small glob matcher that packs a punch.
JavaScript
24
star
39

worktank

A simple isomorphic library for executing functions inside WebWorkers or Node Threads pools.
TypeScript
23
star
40

alfred-spaces-workflow

Alfred workflow that, used in conjunction with my Phoenix setup, gives you a spaces switcher.
23
star
41

vscode-markdown-todo

Manage todo lists inside markdown files with ease.
TypeScript
22
star
42

noren

A minimal HTTP server with good developer-experience and performance, for Node and beyond.
TypeScript
21
star
43

pollex

A tiny polling-based filesystem watcher that tries to be efficient.
TypeScript
21
star
44

vscode-debug-launcher

Start debugging, without having to define any tasks or launch configurations, even from the terminal.
TypeScript
20
star
45

gitman

A simple yet powerful opinionated tool for managing GitHub repositories.
TypeScript
19
star
46

tiny-sqlite3

A tiny cross-platform client for SQLite3, with precompiled binaries as the only third-party dependencies.
JavaScript
19
star
47

vscode-statusbar-debugger

Adds a debugger to the statusbar, less intrusive than the default floating one.
TypeScript
19
star
48

pacco

A bundler for modular and extensible web projects.
JavaScript
18
star
49

vscode-github-notifications-bell

A secure, customizable, statusbar bell that notifies you about notifications on github.
TypeScript
18
star
50

vscode-bump

Bump your project's version and update the changelog. Opinionated but configurable.
TypeScript
16
star
51

vscode-open-in-application

Open an arbitrary file in its default app, or the app you want.
TypeScript
15
star
52

monex

Execute a script and restart it whenever it crashes or a watched file changes.
TypeScript
15
star
53

tiny-encryptor

A tiny opinionated isomorphic library for encrypting and decrypting with ease.
JavaScript
14
star
54

awesome-template

Curated list of templates for Template.
14
star
55

jsonc-simple-parser

A simple JSON parser that supports comments and optional trailing commas.
JavaScript
14
star
56

secret

The simplest command to encrypt/decrypt a file, useful for committing encrypted ".env" files to version control, among other things.
TypeScript
14
star
57

specialist

A library that helps you write tiny, fast, bundled and beautiful CLI apps that can automatically check for updates.
JavaScript
13
star
58

zstandard-wasm

A fast and small port of Zstandard to WASM. (Decompress-only for now).
C
13
star
59

dettle

A tiny fully-featured debounce and throttle implementation.
TypeScript
13
star
60

is

The definitive collection of is* functions for runtime type checking. Lodash-compatible, tree-shakable, with types.
JavaScript
12
star
61

base256-encoding

Base256 encoding, the most memory-efficient encoding possible in JavaScript.
JavaScript
12
star
62

zeptoid

A tiny isomorphic fast function for generating a cryptographically random hex string.
TypeScript
11
star
63

vscode-browser-refresh

Refresh the browser with a ⌘R, right from Code. No need to switch focus to it.
TypeScript
10
star
64

tiny-levenshtein

A tiny implementation of the Levenshtein edit distance algorithm.
TypeScript
10
star
65

json-sorted-stringify

Alternative JSON.stringify function with sorted keys, so the output is stable.
JavaScript
10
star
66

huffy

A tiny compression library based on Huffman coding.
TypeScript
10
star
67

amuchina

A work-in-progress HTML sanitizer that strives for: performance like window.Sanitizer, readiness like DOMPurify, and ability to run in a WebWorker like neither of those.
TypeScript
10
star
68

scex

A simple runner for npm scripts that can execute multiple scripts, in serial or in parallel.
TypeScript
10
star
69

toygrad

A toy library for building simple neural networks which can be serialized to compact JSON.
TypeScript
10
star
70

vscode-optimize-images

Optimize one or all the images in your project using your favorite app.
TypeScript
9
star
71

crypto-puzzle

Basically a proof-of-work generator, this library makes cryptographic puzzles that are arbitrarily expensive to solve.
TypeScript
9
star
72

vscode-open-in-terminal

Adds a few commands for opening the current project in Terminal.
TypeScript
9
star
73

strid

Get a unique string identifier for any input value.
JavaScript
9
star
74

paketo

A tiny library for importing your package.json, with proper types!
TypeScript
9
star
75

grammex

A tiny PEG-like system for building language grammars with regexes.
JavaScript
9
star
76

tiny-parse-argv

A tiny function for parsing process.argv, a modern rewrite of a sensible subset of minimist.
JavaScript
9
star
77

tsex

A little CLI for making TypeScript packages, cleanly and effortlessly.
TypeScript
9
star
78

css-simple-minifier

A CSS minifier that's tiny and very fast.
JavaScript
8
star
79

vscode-open-multiple-files

Open all files in a folder at once, optionally filtering by a glob.
TypeScript
8
star
80

path-prop

Fast library for manipulating plain objects using paths.
JavaScript
8
star
81

react-router-static

A dead simple static router for React. Useful for multi-window Electron applications.
TypeScript
8
star
82

base128-encoding

Base128 encoding, the intersection of latin1 and utf-8, which is basically ASCII, the most memory-efficient string encoding that can be written to disk as utf-8 without ballooning in size.
TypeScript
8
star
83

noop-tag

A noop template literal tag, useful for syntax highlighting hints.
JavaScript
7
star
84

vscode-no-unsupported

An extension for removing [Unsupported] from the titlebar
TypeScript
7
star
85

tiny-webcrypto

A tiny isomorphic WebCrypto object, it just gives you the native one the current platform provides.
TypeScript
7
star
86

csv-simple-parser

A simple, fast and configurable CSV parser.
JavaScript
7
star
87

performance-interval

A precise implementation of setInterval that supports sub-millisecond intervals.
TypeScript
7
star
88

json-archive

Simple archive format based on JSON.
TypeScript
7
star
89

alfred-eject-workflow

Alfred workflow for ejecting mounted drives.
7
star
90

tiny-jsonc

An absurdly small JSONC parser.
JavaScript
7
star
91

chrome-window-session

Save each window as a separate session, automatically.
TypeScript
6
star
92

template-electron

A template for starting a new electron app quickly.
TypeScript
6
star
93

electron-about

Simple standalone about window for Electron.
TypeScript
6
star
94

bob-wasm

A port of Svgbob to WASM.
TypeScript
6
star
95

benchloop

Simple benchmarking library with a pretty output.
TypeScript
6
star
96

worktank-loader

WebPack plugin for WorkTank which enables you to execute whole files in a worker pool, transparently.
TypeScript
6
star
97

html-segmentator

A small library for splitting an HTML string into its top-level sections. Based on html5parser.
TypeScript
6
star
98

vscode-git-history

View or diff against previous versions of the current file.
TypeScript
6
star
99

uint8-concat

Concatenate mutiple Uint8Arrays super efficiently.
JavaScript
6
star
100

configuration

Performant and feature rich library for managing configurations/settings.
JavaScript
6
star