@trenskow/atomic-write-stream 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,11 @@
1
+ Copyright 2025 Kristian Trenskow
2
+
3
+ Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
4
+
5
+ 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
6
+
7
+ 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
8
+
9
+ 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
10
+
11
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package/README.md ADDED
@@ -0,0 +1,23 @@
1
+ @trenskow/atomic-write-stream
2
+ ----
3
+
4
+ A writeable file stream that writes atomically.
5
+
6
+ # Usage
7
+
8
+ Usage is works in exactly the same way as Node's build-in `createWriteStream` except it writes atomically and supports some options.
9
+
10
+ ````javascript
11
+ import createAtomicWriteStream from '@trenskow/atomic-write-stram';
12
+
13
+ const stream = createAtomicWriteStream('hello.txt', {
14
+ tmpDirectory: '/some/tmp/directory' /* defaults to `os.tmpdir()`. */
15
+ });
16
+
17
+ stream.write('Hello, World!');
18
+ stream.end();
19
+ ````
20
+
21
+ # LICENSE
22
+
23
+ See license in LICENSE.
@@ -0,0 +1,54 @@
1
+ import globals from 'globals';
2
+ import path from 'node:path';
3
+ import { fileURLToPath } from 'node:url';
4
+ import js from '@eslint/js';
5
+ import { FlatCompat } from '@eslint/eslintrc';
6
+
7
+ const __filename = fileURLToPath(import.meta.url);
8
+ const __dirname = path.dirname(__filename);
9
+ const compat = new FlatCompat({
10
+ baseDirectory: __dirname,
11
+ recommendedConfig: js.configs.recommended,
12
+ allConfig: js.configs.all
13
+ });
14
+
15
+ export default [...compat.extends('eslint:recommended'), {
16
+ languageOptions: {
17
+ globals: {
18
+ ...globals.node,
19
+ ...globals.mocha,
20
+ },
21
+
22
+ ecmaVersion: 'latest',
23
+ sourceType: 'module',
24
+ },
25
+
26
+ rules: {
27
+ indent: ['error', 'tab', {
28
+ SwitchCase: 1,
29
+ }],
30
+
31
+ 'linebreak-style': ['error', 'unix'],
32
+ quotes: ['error', 'single'],
33
+ semi: ['error', 'always'],
34
+
35
+ 'no-console': ['error', {
36
+ allow: ['warn', 'error', 'info'],
37
+ }],
38
+
39
+ 'no-unused-vars': ['error', {
40
+ argsIgnorePattern: '^_',
41
+ }],
42
+
43
+ 'no-empty': ['error', {
44
+ allowEmptyCatch: true,
45
+ }],
46
+
47
+ 'no-trailing-spaces': ['error', {
48
+ ignoreComments: true,
49
+ }],
50
+
51
+ 'require-atomic-updates': 'off',
52
+ 'eol-last': ['error', 'always'],
53
+ },
54
+ }];
package/index.js ADDED
@@ -0,0 +1,11 @@
1
+ //
2
+ // index.js
3
+ // @trenskow/signed-stream
4
+ //
5
+ // Created by Kristian Trenskow on 2025/01/01
6
+ // See license in LICENSE.
7
+ //
8
+
9
+ import createAtomicWriteStream from './lib/index.js';
10
+
11
+ export default createAtomicWriteStream;
package/lib/index.js ADDED
@@ -0,0 +1,92 @@
1
+ //
2
+ // index.js
3
+ // @trenskow/signed-stream
4
+ //
5
+ // Created by Kristian Trenskow on 2025/01/01
6
+ // See license in LICENSE.
7
+ //
8
+
9
+ import { createWriteStream } from 'fs';
10
+ import { rename, unlink, stat } from 'fs/promises';
11
+ import { tmpdir } from 'os';
12
+ import { basename } from 'path';
13
+ import { randomBytes } from 'crypto';
14
+ import { Transform } from 'stream';
15
+
16
+ class AtomicStream extends Transform {
17
+
18
+ constructor(path, { tmpDirectory = tmpdir() } = {}) {
19
+
20
+ super();
21
+
22
+ this._path = path;
23
+ this._birthPath = `${tmpDirectory}/${basename(path)}.${randomBytes(4).toString('hex')}`;
24
+ this._gravePath = `${tmpDirectory}/${basename(path)}.${randomBytes(4).toString('hex')}`;
25
+
26
+ this.once('error', () => this._cleanup());
27
+
28
+ }
29
+
30
+ _cleanup() {
31
+ unlink(this._birthPath).catch(() => {});
32
+ }
33
+
34
+ _finish(callback) {
35
+
36
+ (async () => {
37
+
38
+ let isOverwrite = true;
39
+
40
+ try {
41
+ await stat(this._path);
42
+ } catch (_) {
43
+ isOverwrite = false;
44
+ }
45
+
46
+ if (isOverwrite) {
47
+ try {
48
+ await rename(this._path, this._gravePath);
49
+ } catch (error) {
50
+ this._cleanup();
51
+ throw error;
52
+ }
53
+ }
54
+
55
+ try {
56
+ await rename(this._birthPath, this._path);
57
+ } catch (error) {
58
+
59
+ if (isOverwrite) {
60
+ await rename(this._gravePath, this._path);
61
+ }
62
+
63
+ this._cleanup();
64
+
65
+ throw error;
66
+
67
+ }
68
+
69
+ if (isOverwrite) {
70
+
71
+ try {
72
+ await unlink(this._gravePath);
73
+ } catch (_) { }
74
+
75
+ }
76
+
77
+ })().then(() => callback()).catch((error) => callback(error));
78
+
79
+ }
80
+
81
+ };
82
+
83
+ export default createAtomicWriteStream = (path, { tmpDirectory = tmpdir() } = {}) => {
84
+
85
+ const writeStream = createWriteStream(path);
86
+ const atomicStream = new AtomicStream(path, { tmpDirectory });
87
+
88
+ atomicStream.pipe(writeStream);
89
+
90
+ return atomicStream;
91
+
92
+ };
package/package.json ADDED
@@ -0,0 +1,32 @@
1
+ {
2
+ "name": "@trenskow/atomic-write-stream",
3
+ "version": "0.1.0",
4
+ "description": "A writeable file stream that writes atomically.",
5
+ "main": "index.js",
6
+ "scripts": {
7
+ "test": "echo \"Error: no test specified\" && exit 1"
8
+ },
9
+ "repository": {
10
+ "type": "git",
11
+ "url": "git+https://github.com/trenskow/atomic-write-stream.git"
12
+ },
13
+ "keywords": [
14
+ "createWriteStream",
15
+ "write",
16
+ "stream",
17
+ "atomic",
18
+ "file"
19
+ ],
20
+ "author": "Kristian Trenskow <this.is@kristians.email>",
21
+ "license": "BSD-3-Clause",
22
+ "bugs": {
23
+ "url": "https://github.com/trenskow/atomic-write-stream/issues"
24
+ },
25
+ "homepage": "https://github.com/trenskow/atomic-write-stream#readme",
26
+ "devDependencies": {
27
+ "@eslint/eslintrc": "^3.2.0",
28
+ "@eslint/js": "^9.17.0",
29
+ "eslint": "^9.17.0",
30
+ "globals": "^15.14.0"
31
+ }
32
+ }