@alwatr/node-fs 1.0.0-beta.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/CHANGELOG.md ADDED
@@ -0,0 +1,25 @@
1
+ # Change Log
2
+
3
+ All notable changes to this project will be documented in this file.
4
+ See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
5
+
6
+ # 1.0.0-beta.0 (2024-01-08)
7
+
8
+ ### Bug Fixes
9
+
10
+ * **node-fs:** Update import statement for make-file module ([7bddaa0](https://github.com/Alwatr/nanolib/commit/7bddaa0d629c304fedd07c4022d7503aa9b974b6)) by @AliMD
11
+
12
+ ### Features
13
+
14
+ * **node-fs:** Add make-file-bench demo script ([ca3a57a](https://github.com/Alwatr/nanolib/commit/ca3a57a31de5a8b9c76c9d33cb9755809f09a335)) by @AliMD
15
+ * **node-fs:** base package ([74cbe48](https://github.com/Alwatr/nanolib/commit/74cbe4821c991d1f6c3d5805b29602b922c3f505)) by @njfamirm
16
+ * **node-fs:** copy from store ([5c23e01](https://github.com/Alwatr/nanolib/commit/5c23e01e42d438c15dcd272d2cc351527865c86c)) by @njfamirm
17
+ * **node-fs:** definePackage and logger ([3880703](https://github.com/Alwatr/nanolib/commit/38807039895c784be6168111506b0721980cbb29)) by @njfamirm
18
+ * **node-fs:** demo ([31f3740](https://github.com/Alwatr/nanolib/commit/31f37405a7bb2b4b02440de7f96f5cc8a474aba9)) by @njfamirm
19
+ * **node-fs:** enhance json types ([e85d927](https://github.com/Alwatr/nanolib/commit/e85d9276374a8c5171901791a3a43acad64843a6)) by @AliMD
20
+ * **node-fs:** enhance writeJson type ([9010c72](https://github.com/Alwatr/nanolib/commit/9010c723b1f34cd647f157466554b312fc84a1d3)) by @AliMD
21
+ * **node-fs:** makeFile ([186ba09](https://github.com/Alwatr/nanolib/commit/186ba09822bddfe200a0ac4725063785cadd0999)) by @njfamirm
22
+ * **node-fs:** readFile under asyncQueue ([ab12153](https://github.com/Alwatr/nanolib/commit/ab12153281600a4ac90ef627811b430a95140ddd)) by @AliMD
23
+ * **node-fs:** rewrite new writeFile method ([7534ed1](https://github.com/Alwatr/nanolib/commit/7534ed158cdfe1ee593050255c17449960b13001)) by @AliMD
24
+ * **node-fs:** writeFile under asyncQueue ([6d8b3d7](https://github.com/Alwatr/nanolib/commit/6d8b3d7953938fc954e8ce350206555030560978)) by @AliMD
25
+ * **node-fs:** writeJson method ([581d4f9](https://github.com/Alwatr/nanolib/commit/581d4f958ccb262c13f23881151616b7ec5e93ee)) by @AliMD
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2022 S. Ali Mihandoost
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,37 @@
1
+ # Node FS
2
+
3
+ Enhanced file system operations in Node.js with asynchronous queue to prevent parallel writes.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ yarn add @alwatr/node-fs
9
+ ```
10
+
11
+ ## Features
12
+
13
+ - Checks if a directory exists. If it doesn't, it creates the directory and all necessary subdirectories.
14
+ - Before writing a file successfully, first writes it to a temporary path (`path.tmp`).
15
+ - If a file already exists, renames and keeps the existing file at a backup path (`path.bak`).
16
+ - If a write operation fails, the original file remains unchanged.
17
+ - Includes `readJson` and `writeJson` functions that automatically parse and stringify JSON data.
18
+ - Supports both synchronous and asynchronous read/write operations.
19
+ - An asynchronous queue is used to prevent simultaneous write operations.
20
+ - Fully written in TypeScript, includes type definitions.
21
+ - Separate builds are provided for ESModule and CommonJS.
22
+ - Zero dependencies, except for the nanolib library.
23
+ - Includes a beautiful log feature, which uses the [logger](https://github.com/Alwatr/nanolib/tree/next/packages/logger) package from nanolib.
24
+
25
+ ## Usage
26
+
27
+ ```typescript
28
+ import {writeJson} from '@alwatr/node-fs';
29
+
30
+ const path = 'file.json';
31
+ await writeJson(path, {a: 1}); // wait to finish
32
+ writeJson(path, {a: 2}); // asynchronous write in queue
33
+ writeJson(path, {a: 3}); // asynchronous write in queue
34
+
35
+ const data = await readJson(path); // automatically wait for the queue to finish
36
+ console.log(data.a); // 3
37
+ ```
@@ -0,0 +1,4 @@
1
+ import { AsyncQueue } from '@alwatr/async-queue';
2
+ export declare const logger: import("@alwatr/logger").AlwatrLogger;
3
+ export declare const asyncQueue: AsyncQueue;
4
+ //# sourceMappingURL=common.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"common.d.ts","sourceRoot":"","sources":["../src/common.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,UAAU,EAAC,MAAM,qBAAqB,CAAC;AAK/C,eAAO,MAAM,MAAM,uCAAwD,CAAC;AAE5E,eAAO,MAAM,UAAU,YAAmB,CAAC"}
package/dist/json.d.ts ADDED
@@ -0,0 +1,26 @@
1
+ import type { Dictionary } from '@alwatr/type-helper';
2
+ /**
3
+ * Parse json string.
4
+ *
5
+ * @param content - json string
6
+ * @returns json object
7
+ * @example
8
+ * ```typescript
9
+ * const json = parseJson('{"a":1,"b":2}');
10
+ * console.log(json.a); // 1
11
+ * ```
12
+ */
13
+ export declare function parseJson<T extends Dictionary>(content: string): T;
14
+ /**
15
+ * Stringify json object.
16
+ *
17
+ * @param data - json object
18
+ * @returns json string
19
+ * @example
20
+ * ```typescript
21
+ * const json = jsonStringify({a:1, b:2});
22
+ * console.log(json); // '{"a":1,"b":2}'
23
+ * ```
24
+ */
25
+ export declare function jsonStringify<T extends Dictionary>(data: T): string;
26
+ //# sourceMappingURL=json.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"json.d.ts","sourceRoot":"","sources":["../src/json.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,qBAAqB,CAAC;AAEtD;;;;;;;;;;GAUG;AACH,wBAAgB,SAAS,CAAC,CAAC,SAAS,UAAU,EAAE,OAAO,EAAE,MAAM,GAAG,CAAC,CAQlE;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,aAAa,CAAC,CAAC,SAAS,UAAU,EAAE,IAAI,EAAE,CAAC,GAAG,MAAM,CAQnE"}
package/dist/main.cjs ADDED
@@ -0,0 +1,3 @@
1
+ /* @alwatr/node-fs v1.0.0-beta.0 */
2
+ "use strict";var l=Object.defineProperty;var M=Object.getOwnPropertyDescriptor;var P=Object.getOwnPropertyNames;var b=Object.prototype.hasOwnProperty;var k=(r,e)=>{for(var o in e)l(r,o,{get:e[o],enumerable:!0})},A=(r,e,o,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of P(e))!b.call(r,a)&&a!==o&&l(r,a,{get:()=>e[a],enumerable:!(n=M(e,a))||n.enumerable});return r};var h=r=>A(l({},"__esModule",{value:!0}),r);var N={};k(N,{existsSync:()=>v.existsSync,makeEmptyFile:()=>Q,readFile:()=>d,readFileSync:()=>m,readJson:()=>j,resolve:()=>J.resolve,unlink:()=>D.unlink,writeFile:()=>u,writeFileSync:()=>y,writeJson:()=>O});module.exports=h(N);var w=require("@alwatr/async-queue"),x=require("@alwatr/logger"),i=(0,x.definePackage)("@alwatr/node-fs","1.0.0-beta.0"),c=new w.AsyncQueue;var F=require("fs"),_=require("fs/promises"),f=require("@alwatr/flat-string");function m(r){i.logMethodArgs?.("readFileSync","..."+r.slice(-32));try{return(0,f.flatString)((0,F.readFileSync)(r,{encoding:"utf-8",flag:"r"}))}catch(e){throw i.error("readFileSync","read_file_failed",{path:r},e),new Error("read_file_failed",{cause:e.cause})}}function d(r){return i.logMethodArgs?.("readFile","..."+r.slice(-32)),c.push(r,async()=>{try{return(0,f.flatString)(await(0,_.readFile)(r,{encoding:"utf-8",flag:"r"}))}catch(e){throw i.error("readFile","read_file_failed",{path:r},e),new Error("read_file_failed",{cause:e.cause})}})}var t=require("fs"),s=require("fs/promises"),g=require("path");function y(r,e){i.logMethodArgs?.("writeFileSync","..."+r.slice(-32));try{let o=(0,t.existsSync)(r);if(!o){let n=(0,g.dirname)(r);(0,t.existsSync)(n)||(0,t.mkdirSync)(n,{recursive:!0})}(0,t.writeFileSync)(r+".tmp",e,{encoding:"utf-8",flag:"w"}),o&&(0,t.renameSync)(r,r+".bak"),(0,t.renameSync)(r+".tmp",r),i.logOther?.("writeFileSync success","..."+r.slice(-32))}catch(o){throw i.error("writeFileSync","write_file_failed",{path:r},o),new Error("write_file_failed",{cause:o.cause})}}function u(r,e){return i.logMethodArgs?.("writeFile","..."+r.slice(-32)),c.push(r,async()=>{try{i.logOther?.("writeFile start","..."+r.slice(-32));let o=(0,t.existsSync)(r);if(!o){let n=(0,g.dirname)(r);(0,t.existsSync)(n)||await(0,s.mkdir)(n,{recursive:!0})}await(0,s.writeFile)(r+".tmp",e,{encoding:"utf-8",flag:"w"}),o&&await(0,s.rename)(r,r+".bak"),await(0,s.rename)(r+".tmp",r),i.logOther?.("writeFile success","..."+r.slice(-32))}catch(o){throw i.error("writeFile","write_file_failed",{path:r},o),new Error("write_file_failed",{cause:o.cause})}})}function p(r){try{return JSON.parse(r)}catch(e){throw i.error("parseJson","invalid_json",e),new Error("invalid_json",{cause:e.cause})}}function S(r){try{return JSON.stringify(r)}catch(e){throw i.error("jsonStringify","stringify_failed",e),new Error("stringify_failed",{cause:e.cause})}}function j(r,e=!1){return i.logMethodArgs?.("readJson",{path:r.slice(-32),sync:e}),e===!0?p(m(r)):d(r).then(o=>p(o))}var T=require("@alwatr/flat-string");function O(r,e,o=!1){i.logMethodArgs?.("writeJson","..."+r.slice(-32));let n=(0,T.flatString)(S(e));return o===!0?y(r,n):u(r,n)}var E=require("fs/promises");async function Q(r){return i.logMethodArgs?.("makeEmptyFile","..."+r.slice(-32)),(await(0,E.open)(r,"w")).close()}var J=require("path"),v=require("fs"),D=require("fs/promises");0&&(module.exports={existsSync,makeEmptyFile,readFile,readFileSync,readJson,resolve,unlink,writeFile,writeFileSync,writeJson});
3
+ //# sourceMappingURL=main.cjs.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/main.ts", "../src/common.ts", "../src/read-file.ts", "../src/write-file.ts", "../src/json.ts", "../src/read-json.ts", "../src/write-json.ts", "../src/make-file.ts"],
4
+ "sourcesContent": ["export * from './read-file';\nexport * from './write-file';\nexport * from './read-json';\nexport * from './write-json';\nexport * from './make-file';\n\nexport {resolve} from 'node:path';\nexport {existsSync} from 'node:fs';\nexport {unlink} from 'node:fs/promises';\n", "import {AsyncQueue} from '@alwatr/async-queue';\nimport {definePackage} from '@alwatr/logger';\n\nimport type {} from '@alwatr/nano-build';\n\nexport const logger = definePackage('@alwatr/node-fs', __package_version__);\n\nexport const asyncQueue = new AsyncQueue();\n", "import {readFileSync as readFileSync_} from 'node:fs';\nimport {readFile as readFile_} from 'node:fs/promises';\n\nimport {flatString} from '@alwatr/flat-string';\n\nimport {asyncQueue, logger} from './common';\n\n/**\n * Enhanced read File (Synchronous).\n *\n * @param path - file path\n * @returns file content\n * @example\n * ```typescript\n * const fileContent = readFileSync('./file.txt', sync);\n * ```\n */\nexport function readFileSync(path: string): string {\n logger.logMethodArgs?.('readFileSync', '...' + path.slice(-32));\n // if (!existsSync(path)) throw new Error('file_not_found');\n try {\n return flatString(readFileSync_(path, {encoding: 'utf-8', flag: 'r'}));\n }\n catch (err) {\n logger.error('readFileSync', 'read_file_failed', {path}, err);\n throw new Error('read_file_failed', {cause: (err as Error).cause});\n }\n}\n\n/**\n * Enhanced read File (Asynchronous).\n *\n * - If writing queue is running for target path, it will wait for it to finish.\n *\n * @param path - file path\n * @returns file content\n * @example\n * ```typescript\n * const fileContent = await readFile('./file.txt', sync);\n * ```\n */\nexport function readFile(path: string): Promise<string> {\n logger.logMethodArgs?.('readFile', '...' + path.slice(-32));\n // if (!existsSync(path)) throw new Error('file_not_found');\n return asyncQueue.push(path, async () => {\n try {\n return flatString(await readFile_(path, {encoding: 'utf-8', flag: 'r'}));\n }\n catch (err) {\n logger.error('readFile', 'read_file_failed', {path}, err);\n throw new Error('read_file_failed', {cause: (err as Error).cause});\n }\n });\n}\n", "import {writeFileSync as writeFileSync_, existsSync, mkdirSync, renameSync} from 'node:fs';\nimport {mkdir, rename, writeFile as writeFile_} from 'node:fs/promises';\nimport {dirname} from 'node:path';\n\nimport {asyncQueue, logger} from './common';\n\n/**\n * Enhanced write file (Synchronous).\n *\n * - If directory not exists, create it recursively.\n * - Write file to `path.tmp` before write success.\n * - If file exists, renamed (keep) to `path.bak`.\n * - If write failed, original file will not be changed.\n *\n * @param path - file path\n * @param content - file content\n * @example\n * ```typescript\n * writeFileSync('./file.txt', 'Hello World!');\n * ```\n */\nexport function writeFileSync(path: string, content: string): void {\n logger.logMethodArgs?.('writeFileSync', '...' + path.slice(-32));\n try {\n const pathExists = existsSync(path);\n if (!pathExists) {\n const dir = dirname(path);\n if (!existsSync(dir)) {\n mkdirSync(dir, {recursive: true});\n }\n }\n writeFileSync_(path + '.tmp', content, {encoding: 'utf-8', flag: 'w'});\n if (pathExists) {\n renameSync(path, path + '.bak');\n }\n renameSync(path + '.tmp', path);\n logger.logOther?.('writeFileSync success', '...' + path.slice(-32));\n }\n catch (err) {\n logger.error('writeFileSync', 'write_file_failed', {path}, err);\n throw new Error('write_file_failed', {cause: (err as Error).cause});\n }\n}\n\n/**\n * Enhanced write file (Asynchronous).\n *\n * - If directory not exists, create it recursively.\n * - Write file to `path.tmp` before write success.\n * - If file exists, renamed (keep) to `path.bak`.\n * - If write failed, original file will not be changed.\n *\n * @param path - file path\n * @param content - file content\n * @example\n * ```typescript\n * await writeFile('./file.txt', 'Hello World!');\n * ```\n */\nexport function writeFile(path: string, content: string): Promise<void> {\n logger.logMethodArgs?.('writeFile', '...' + path.slice(-32));\n return asyncQueue.push(path, async () => {\n try {\n logger.logOther?.('writeFile start', '...' + path.slice(-32));\n const pathExists = existsSync(path);\n if (!pathExists) {\n const dir = dirname(path);\n if (!existsSync(dir)) {\n await mkdir(dir, {recursive: true});\n }\n }\n await writeFile_(path + '.tmp', content, {encoding: 'utf-8', flag: 'w'});\n if (pathExists) {\n await rename(path, path + '.bak');\n }\n await rename(path + '.tmp', path);\n logger.logOther?.('writeFile success', '...' + path.slice(-32));\n }\n catch (err) {\n logger.error('writeFile', 'write_file_failed', {path}, err);\n throw new Error('write_file_failed', {cause: (err as Error).cause});\n }\n });\n}\n", "import {logger} from './common';\n\nimport type { Dictionary } from '@alwatr/type-helper';\n\n/**\n * Parse json string.\n *\n * @param content - json string\n * @returns json object\n * @example\n * ```typescript\n * const json = parseJson('{\"a\":1,\"b\":2}');\n * console.log(json.a); // 1\n * ```\n */\nexport function parseJson<T extends Dictionary>(content: string): T {\n try {\n return JSON.parse(content);\n }\n catch (err) {\n logger.error('parseJson', 'invalid_json', err);\n throw new Error('invalid_json', {cause: (err as Error).cause});\n }\n}\n\n/**\n * Stringify json object.\n *\n * @param data - json object\n * @returns json string\n * @example\n * ```typescript\n * const json = jsonStringify({a:1, b:2});\n * console.log(json); // '{\"a\":1,\"b\":2}'\n * ```\n */\nexport function jsonStringify<T extends Dictionary>(data: T): string {\n try {\n return JSON.stringify(data);\n }\n catch (err) {\n logger.error('jsonStringify', 'stringify_failed', err);\n throw new Error('stringify_failed', {cause: (err as Error).cause});\n }\n}\n", "import {logger} from './common';\nimport {parseJson} from './json';\nimport {readFile, readFileSync} from './read-file';\n\nimport type {Dictionary, MaybePromise} from '@alwatr/type-helper';\n\n/**\n * Enhanced read json file (async).\n *\n * @param path - file path\n * @returns json object\n * @example\n * ```typescript\n * const fileContent = await readJson('./file.json');\n * ```\n */\nexport function readJson<T extends Dictionary>(path: string): Promise<T>;\n/**\n * Enhanced read json file (sync).\n *\n * @param path - file path\n * @param sync - sync mode\n * @returns json object\n * @example\n * ```typescript\n * const fileContent = readJson('./file.json', true);\n * ```\n */\nexport function readJson<T extends Dictionary>(path: string, sync: true): T;\n/**\n * Enhanced read json file.\n *\n * @param path - file path\n * @param sync - sync mode\n * @returns json object\n * @example\n * ```typescript\n * const fileContent = await readJson('./file.json', sync);\n * ```\n */\nexport function readJson<T extends Dictionary>(path: string, sync: boolean): MaybePromise<T>;\n/**\n * Enhanced read json file.\n *\n * @param path - file path\n * @param sync - sync mode\n * @returns json object\n * @example\n * ```typescript\n * const fileContent = await readJson('./file.json');\n * ```\n */\nexport function readJson<T extends Dictionary>(path: string, sync = false): MaybePromise<T> {\n logger.logMethodArgs?.('readJson', {path: path.slice(-32), sync});\n if (sync === true) {\n return parseJson<T>(readFileSync(path));\n }\n else {\n return readFile(path).then((content) => parseJson<T>(content));\n }\n}\n", "import {flatString} from '@alwatr/flat-string';\n\nimport {logger} from './common';\nimport {jsonStringify} from './json';\nimport {writeFile, writeFileSync} from './write-file';\n\nimport type {Dictionary, MaybePromise} from '@alwatr/type-helper';\n\n/**\n * Enhanced write json file (Asynchronous).\n *\n * @param path - file path\n * @param data - json object\n * @example\n * ```typescript\n * await writeJsonFile('./file.json', { a:1, b:2, c:3 });\n * ```\n */\nexport function writeJson<T extends Dictionary>(path: string, data: T, sync?: false): Promise<void>;\n/**\n * Enhanced write json file (Synchronous).\n *\n * @param path - file path\n * @param data - json object\n * @param sync - sync mode\n * @example\n * ```typescript\n * writeJsonFile('./file.json', { a:1, b:2, c:3 }, true);\n * ```\n */\nexport function writeJson<T extends Dictionary>(path: string, data: T, sync: true): void;\n/**\n * Enhanced write json file.\n *\n * @param path - file path\n * @param data - json object\n * @param sync - sync mode\n * @example\n * ```typescript\n * await writeJsonFile('./file.json', { a:1, b:2, c:3 }, sync);\n * ```\n */\nexport function writeJson<T extends Dictionary>(path: string, data: T, sync: boolean): MaybePromise<void>;\n/**\n * Enhanced write json file.\n *\n * @param path - file path\n * @param data - json object\n * @param sync - sync mode\n * @example\n * ```typescript\n * await writeJsonFile('./file.json', { a:1, b:2, c:3 });\n * ```\n */\nexport function writeJson<T extends Dictionary>(path: string, data: T, sync = false): MaybePromise<void> {\n logger.logMethodArgs?.('writeJson', '...' + path.slice(-32));\n const content = flatString(jsonStringify(data));\n return sync === true ? writeFileSync(path, content) : writeFile(path, content);\n}\n", "import {open} from 'node:fs/promises';\n\nimport {logger} from './common';\n\n/**\n * Make empty file.\n *\n * @param path - file path\n *\n * @example\n * ```ts\n * await makeFile('./file.txt');\n * ```\n */\nexport async function makeEmptyFile(path: string): Promise<void> {\n logger.logMethodArgs?.('makeEmptyFile', '...' + path.slice(-32));\n return (await open(path, 'w')).close();\n}\n"],
5
+ "mappings": ";yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,+CAAAE,EAAA,aAAAC,EAAA,iBAAAC,EAAA,aAAAC,EAAA,wDAAAC,EAAA,kBAAAC,EAAA,cAAAC,IAAA,eAAAC,EAAAT,GCAA,IAAAU,EAAyB,+BACzBC,EAA4B,0BAIfC,KAAS,iBAAc,kBAAmB,cAAmB,EAE7DC,EAAa,IAAI,aCP9B,IAAAC,EAA4C,cAC5CC,EAAoC,uBAEpCC,EAAyB,+BAclB,SAASC,EAAaC,EAAsB,CACjDC,EAAO,gBAAgB,eAAgB,MAAQD,EAAK,MAAM,GAAG,CAAC,EAE9D,GAAI,CACF,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AAK,CAAC,CACnE,CACF,CCQO,SAASI,EAA+BC,EAAcC,EAAO,GAAwB,CAE1F,OADAC,EAAO,gBAAgB,WAAY,CAAC,KAAMF,EAAK,MAAM,GAAG,EAAG,KAAAC,CAAI,CAAC,EAC5DA,IAAS,GACJE,EAAaC,EAAaJ,CAAI,CAAC,EAG/BK,EAASL,CAAI,EAAE,KAAMM,GAAYH,EAAaG,CAAO,CAAC,CAEjE,CC5DA,IAAAC,EAAyB,+BAsDlB,SAASC,EAAgCC,EAAcC,EAASC,EAAO,GAA2B,CACvGC,EAAO,gBAAgB,YAAa,MAAQH,EAAK,MAAM,GAAG,CAAC,EAC3D,IAAMI,KAAU,cAAWC,EAAcJ,CAAI,CAAC,EAC9C,OAAOC,IAAS,GAAOI,EAAcN,EAAMI,CAAO,EAAIG,EAAUP,EAAMI,CAAO,CAC/E,CC1DA,IAAAI,EAAmB,uBAcnB,eAAsBC,EAAcC,EAA6B,CAC/D,OAAAC,EAAO,gBAAgB,gBAAiB,MAAQD,EAAK,MAAM,GAAG,CAAC,GACvD,QAAM,QAAKA,EAAM,GAAG,GAAG,MAAM,CACvC,CPXA,IAAAE,EAAsB,gBACtBC,EAAyB,cACzBC,EAAqB",
6
+ "names": ["main_exports", "__export", "makeEmptyFile", "readFile", "readFileSync", "readJson", "writeFile", "writeFileSync", "writeJson", "__toCommonJS", "import_async_queue", "import_logger", "logger", "asyncQueue", "import_node_fs", "import_promises", "import_flat_string", "readFileSync", "path", "logger", "readFileSync_", "err", "readFile", "asyncQueue", "readFile_", "import_node_fs", "import_promises", "import_node_path", "writeFileSync", "path", "content", "logger", "pathExists", "dir", "writeFileSync_", "err", "writeFile", "asyncQueue", "writeFile_", "parseJson", "content", "err", "logger", "jsonStringify", "data", "readJson", "path", "sync", "logger", "parseJson", "readFileSync", "readFile", "content", "import_flat_string", "writeJson", "path", "data", "sync", "logger", "content", "jsonStringify", "writeFileSync", "writeFile", "import_promises", "makeEmptyFile", "path", "logger", "import_node_path", "import_node_fs", "import_promises"]
7
+ }
package/dist/main.d.ts ADDED
@@ -0,0 +1,12 @@
1
+ /// <reference types="node" />
2
+ /// <reference types="node" />
3
+ /// <reference types="node" />
4
+ export * from './read-file';
5
+ export * from './write-file';
6
+ export * from './read-json';
7
+ export * from './write-json';
8
+ export * from './make-file';
9
+ export { resolve } from 'node:path';
10
+ export { existsSync } from 'node:fs';
11
+ export { unlink } from 'node:fs/promises';
12
+ //# sourceMappingURL=main.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"main.d.ts","sourceRoot":"","sources":["../src/main.ts"],"names":[],"mappings":";;;AAAA,cAAc,aAAa,CAAC;AAC5B,cAAc,cAAc,CAAC;AAC7B,cAAc,aAAa,CAAC;AAC5B,cAAc,cAAc,CAAC;AAC7B,cAAc,aAAa,CAAC;AAE5B,OAAO,EAAC,OAAO,EAAC,MAAM,WAAW,CAAC;AAClC,OAAO,EAAC,UAAU,EAAC,MAAM,SAAS,CAAC;AACnC,OAAO,EAAC,MAAM,EAAC,MAAM,kBAAkB,CAAC"}
package/dist/main.mjs ADDED
@@ -0,0 +1,3 @@
1
+ /* @alwatr/node-fs v1.0.0-beta.0 */
2
+ import{AsyncQueue as w}from"@alwatr/async-queue";import{definePackage as x}from"@alwatr/logger";var e=x("@alwatr/node-fs","1.0.0-beta.0"),n=new w;import{readFileSync as F}from"fs";import{readFile as _}from"fs/promises";import{flatString as c}from"@alwatr/flat-string";function l(r){e.logMethodArgs?.("readFileSync","..."+r.slice(-32));try{return c(F(r,{encoding:"utf-8",flag:"r"}))}catch(i){throw e.error("readFileSync","read_file_failed",{path:r},i),new Error("read_file_failed",{cause:i.cause})}}function f(r){return e.logMethodArgs?.("readFile","..."+r.slice(-32)),n.push(r,async()=>{try{return c(await _(r,{encoding:"utf-8",flag:"r"}))}catch(i){throw e.error("readFile","read_file_failed",{path:r},i),new Error("read_file_failed",{cause:i.cause})}})}import{writeFileSync as S,existsSync as s,mkdirSync as T,renameSync as m}from"fs";import{mkdir as E,rename as d,writeFile as J}from"fs/promises";import{dirname as g}from"path";function y(r,i){e.logMethodArgs?.("writeFileSync","..."+r.slice(-32));try{let o=s(r);if(!o){let t=g(r);s(t)||T(t,{recursive:!0})}S(r+".tmp",i,{encoding:"utf-8",flag:"w"}),o&&m(r,r+".bak"),m(r+".tmp",r),e.logOther?.("writeFileSync success","..."+r.slice(-32))}catch(o){throw e.error("writeFileSync","write_file_failed",{path:r},o),new Error("write_file_failed",{cause:o.cause})}}function u(r,i){return e.logMethodArgs?.("writeFile","..."+r.slice(-32)),n.push(r,async()=>{try{e.logOther?.("writeFile start","..."+r.slice(-32));let o=s(r);if(!o){let t=g(r);s(t)||await E(t,{recursive:!0})}await J(r+".tmp",i,{encoding:"utf-8",flag:"w"}),o&&await d(r,r+".bak"),await d(r+".tmp",r),e.logOther?.("writeFile success","..."+r.slice(-32))}catch(o){throw e.error("writeFile","write_file_failed",{path:r},o),new Error("write_file_failed",{cause:o.cause})}})}function a(r){try{return JSON.parse(r)}catch(i){throw e.error("parseJson","invalid_json",i),new Error("invalid_json",{cause:i.cause})}}function p(r){try{return JSON.stringify(r)}catch(i){throw e.error("jsonStringify","stringify_failed",i),new Error("stringify_failed",{cause:i.cause})}}function L(r,i=!1){return e.logMethodArgs?.("readJson",{path:r.slice(-32),sync:i}),i===!0?a(l(r)):f(r).then(o=>a(o))}import{flatString as v}from"@alwatr/flat-string";function Y(r,i,o=!1){e.logMethodArgs?.("writeJson","..."+r.slice(-32));let t=v(p(i));return o===!0?y(r,t):u(r,t)}import{open as D}from"fs/promises";async function er(r){return e.logMethodArgs?.("makeEmptyFile","..."+r.slice(-32)),(await D(r,"w")).close()}import{resolve as fr}from"path";import{existsSync as dr}from"fs";import{unlink as yr}from"fs/promises";export{dr as existsSync,er as makeEmptyFile,f as readFile,l as readFileSync,L as readJson,fr as resolve,yr as unlink,u as writeFile,y as writeFileSync,Y as writeJson};
3
+ //# sourceMappingURL=main.mjs.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/common.ts", "../src/read-file.ts", "../src/write-file.ts", "../src/json.ts", "../src/read-json.ts", "../src/write-json.ts", "../src/make-file.ts", "../src/main.ts"],
4
+ "sourcesContent": ["import {AsyncQueue} from '@alwatr/async-queue';\nimport {definePackage} from '@alwatr/logger';\n\nimport type {} from '@alwatr/nano-build';\n\nexport const logger = definePackage('@alwatr/node-fs', __package_version__);\n\nexport const asyncQueue = new AsyncQueue();\n", "import {readFileSync as readFileSync_} from 'node:fs';\nimport {readFile as readFile_} from 'node:fs/promises';\n\nimport {flatString} from '@alwatr/flat-string';\n\nimport {asyncQueue, logger} from './common';\n\n/**\n * Enhanced read File (Synchronous).\n *\n * @param path - file path\n * @returns file content\n * @example\n * ```typescript\n * const fileContent = readFileSync('./file.txt', sync);\n * ```\n */\nexport function readFileSync(path: string): string {\n logger.logMethodArgs?.('readFileSync', '...' + path.slice(-32));\n // if (!existsSync(path)) throw new Error('file_not_found');\n try {\n return flatString(readFileSync_(path, {encoding: 'utf-8', flag: 'r'}));\n }\n catch (err) {\n logger.error('readFileSync', 'read_file_failed', {path}, err);\n throw new Error('read_file_failed', {cause: (err as Error).cause});\n }\n}\n\n/**\n * Enhanced read File (Asynchronous).\n *\n * - If writing queue is running for target path, it will wait for it to finish.\n *\n * @param path - file path\n * @returns file content\n * @example\n * ```typescript\n * const fileContent = await readFile('./file.txt', sync);\n * ```\n */\nexport function readFile(path: string): Promise<string> {\n logger.logMethodArgs?.('readFile', '...' + path.slice(-32));\n // if (!existsSync(path)) throw new Error('file_not_found');\n return asyncQueue.push(path, async () => {\n try {\n return flatString(await readFile_(path, {encoding: 'utf-8', flag: 'r'}));\n }\n catch (err) {\n logger.error('readFile', 'read_file_failed', {path}, err);\n throw new Error('read_file_failed', {cause: (err as Error).cause});\n }\n });\n}\n", "import {writeFileSync as writeFileSync_, existsSync, mkdirSync, renameSync} from 'node:fs';\nimport {mkdir, rename, writeFile as writeFile_} from 'node:fs/promises';\nimport {dirname} from 'node:path';\n\nimport {asyncQueue, logger} from './common';\n\n/**\n * Enhanced write file (Synchronous).\n *\n * - If directory not exists, create it recursively.\n * - Write file to `path.tmp` before write success.\n * - If file exists, renamed (keep) to `path.bak`.\n * - If write failed, original file will not be changed.\n *\n * @param path - file path\n * @param content - file content\n * @example\n * ```typescript\n * writeFileSync('./file.txt', 'Hello World!');\n * ```\n */\nexport function writeFileSync(path: string, content: string): void {\n logger.logMethodArgs?.('writeFileSync', '...' + path.slice(-32));\n try {\n const pathExists = existsSync(path);\n if (!pathExists) {\n const dir = dirname(path);\n if (!existsSync(dir)) {\n mkdirSync(dir, {recursive: true});\n }\n }\n writeFileSync_(path + '.tmp', content, {encoding: 'utf-8', flag: 'w'});\n if (pathExists) {\n renameSync(path, path + '.bak');\n }\n renameSync(path + '.tmp', path);\n logger.logOther?.('writeFileSync success', '...' + path.slice(-32));\n }\n catch (err) {\n logger.error('writeFileSync', 'write_file_failed', {path}, err);\n throw new Error('write_file_failed', {cause: (err as Error).cause});\n }\n}\n\n/**\n * Enhanced write file (Asynchronous).\n *\n * - If directory not exists, create it recursively.\n * - Write file to `path.tmp` before write success.\n * - If file exists, renamed (keep) to `path.bak`.\n * - If write failed, original file will not be changed.\n *\n * @param path - file path\n * @param content - file content\n * @example\n * ```typescript\n * await writeFile('./file.txt', 'Hello World!');\n * ```\n */\nexport function writeFile(path: string, content: string): Promise<void> {\n logger.logMethodArgs?.('writeFile', '...' + path.slice(-32));\n return asyncQueue.push(path, async () => {\n try {\n logger.logOther?.('writeFile start', '...' + path.slice(-32));\n const pathExists = existsSync(path);\n if (!pathExists) {\n const dir = dirname(path);\n if (!existsSync(dir)) {\n await mkdir(dir, {recursive: true});\n }\n }\n await writeFile_(path + '.tmp', content, {encoding: 'utf-8', flag: 'w'});\n if (pathExists) {\n await rename(path, path + '.bak');\n }\n await rename(path + '.tmp', path);\n logger.logOther?.('writeFile success', '...' + path.slice(-32));\n }\n catch (err) {\n logger.error('writeFile', 'write_file_failed', {path}, err);\n throw new Error('write_file_failed', {cause: (err as Error).cause});\n }\n });\n}\n", "import {logger} from './common';\n\nimport type { Dictionary } from '@alwatr/type-helper';\n\n/**\n * Parse json string.\n *\n * @param content - json string\n * @returns json object\n * @example\n * ```typescript\n * const json = parseJson('{\"a\":1,\"b\":2}');\n * console.log(json.a); // 1\n * ```\n */\nexport function parseJson<T extends Dictionary>(content: string): T {\n try {\n return JSON.parse(content);\n }\n catch (err) {\n logger.error('parseJson', 'invalid_json', err);\n throw new Error('invalid_json', {cause: (err as Error).cause});\n }\n}\n\n/**\n * Stringify json object.\n *\n * @param data - json object\n * @returns json string\n * @example\n * ```typescript\n * const json = jsonStringify({a:1, b:2});\n * console.log(json); // '{\"a\":1,\"b\":2}'\n * ```\n */\nexport function jsonStringify<T extends Dictionary>(data: T): string {\n try {\n return JSON.stringify(data);\n }\n catch (err) {\n logger.error('jsonStringify', 'stringify_failed', err);\n throw new Error('stringify_failed', {cause: (err as Error).cause});\n }\n}\n", "import {logger} from './common';\nimport {parseJson} from './json';\nimport {readFile, readFileSync} from './read-file';\n\nimport type {Dictionary, MaybePromise} from '@alwatr/type-helper';\n\n/**\n * Enhanced read json file (async).\n *\n * @param path - file path\n * @returns json object\n * @example\n * ```typescript\n * const fileContent = await readJson('./file.json');\n * ```\n */\nexport function readJson<T extends Dictionary>(path: string): Promise<T>;\n/**\n * Enhanced read json file (sync).\n *\n * @param path - file path\n * @param sync - sync mode\n * @returns json object\n * @example\n * ```typescript\n * const fileContent = readJson('./file.json', true);\n * ```\n */\nexport function readJson<T extends Dictionary>(path: string, sync: true): T;\n/**\n * Enhanced read json file.\n *\n * @param path - file path\n * @param sync - sync mode\n * @returns json object\n * @example\n * ```typescript\n * const fileContent = await readJson('./file.json', sync);\n * ```\n */\nexport function readJson<T extends Dictionary>(path: string, sync: boolean): MaybePromise<T>;\n/**\n * Enhanced read json file.\n *\n * @param path - file path\n * @param sync - sync mode\n * @returns json object\n * @example\n * ```typescript\n * const fileContent = await readJson('./file.json');\n * ```\n */\nexport function readJson<T extends Dictionary>(path: string, sync = false): MaybePromise<T> {\n logger.logMethodArgs?.('readJson', {path: path.slice(-32), sync});\n if (sync === true) {\n return parseJson<T>(readFileSync(path));\n }\n else {\n return readFile(path).then((content) => parseJson<T>(content));\n }\n}\n", "import {flatString} from '@alwatr/flat-string';\n\nimport {logger} from './common';\nimport {jsonStringify} from './json';\nimport {writeFile, writeFileSync} from './write-file';\n\nimport type {Dictionary, MaybePromise} from '@alwatr/type-helper';\n\n/**\n * Enhanced write json file (Asynchronous).\n *\n * @param path - file path\n * @param data - json object\n * @example\n * ```typescript\n * await writeJsonFile('./file.json', { a:1, b:2, c:3 });\n * ```\n */\nexport function writeJson<T extends Dictionary>(path: string, data: T, sync?: false): Promise<void>;\n/**\n * Enhanced write json file (Synchronous).\n *\n * @param path - file path\n * @param data - json object\n * @param sync - sync mode\n * @example\n * ```typescript\n * writeJsonFile('./file.json', { a:1, b:2, c:3 }, true);\n * ```\n */\nexport function writeJson<T extends Dictionary>(path: string, data: T, sync: true): void;\n/**\n * Enhanced write json file.\n *\n * @param path - file path\n * @param data - json object\n * @param sync - sync mode\n * @example\n * ```typescript\n * await writeJsonFile('./file.json', { a:1, b:2, c:3 }, sync);\n * ```\n */\nexport function writeJson<T extends Dictionary>(path: string, data: T, sync: boolean): MaybePromise<void>;\n/**\n * Enhanced write json file.\n *\n * @param path - file path\n * @param data - json object\n * @param sync - sync mode\n * @example\n * ```typescript\n * await writeJsonFile('./file.json', { a:1, b:2, c:3 });\n * ```\n */\nexport function writeJson<T extends Dictionary>(path: string, data: T, sync = false): MaybePromise<void> {\n logger.logMethodArgs?.('writeJson', '...' + path.slice(-32));\n const content = flatString(jsonStringify(data));\n return sync === true ? writeFileSync(path, content) : writeFile(path, content);\n}\n", "import {open} from 'node:fs/promises';\n\nimport {logger} from './common';\n\n/**\n * Make empty file.\n *\n * @param path - file path\n *\n * @example\n * ```ts\n * await makeFile('./file.txt');\n * ```\n */\nexport async function makeEmptyFile(path: string): Promise<void> {\n logger.logMethodArgs?.('makeEmptyFile', '...' + path.slice(-32));\n return (await open(path, 'w')).close();\n}\n", "export * from './read-file';\nexport * from './write-file';\nexport * from './read-json';\nexport * from './write-json';\nexport * from './make-file';\n\nexport {resolve} from 'node:path';\nexport {existsSync} from 'node:fs';\nexport {unlink} from 'node:fs/promises';\n"],
5
+ "mappings": ";AAAA,OAAQ,cAAAA,MAAiB,sBACzB,OAAQ,iBAAAC,MAAoB,iBAIrB,IAAMC,EAASD,EAAc,kBAAmB,cAAmB,EAE7DE,EAAa,IAAIH,ECP9B,OAAQ,gBAAgBI,MAAoB,KAC5C,OAAQ,YAAYC,MAAgB,cAEpC,OAAQ,cAAAC,MAAiB,sBAclB,SAASC,EAAaC,EAAsB,CACjDC,EAAO,gBAAgB,eAAgB,MAAQD,EAAK,MAAM,GAAG,CAAC,EAE9D,GAAI,CACF,OAAOF,EAAWF,EAAcI,EAAM,CAAC,SAAU,QAAS,KAAM,GAAG,CAAC,CAAC,CACvE,OACOE,EAAK,CACV,MAAAD,EAAO,MAAM,eAAgB,mBAAoB,CAAC,KAAAD,CAAI,EAAGE,CAAG,EACtD,IAAI,MAAM,mBAAoB,CAAC,MAAQA,EAAc,KAAK,CAAC,CACnE,CACF,CAcO,SAASC,EAASH,EAA+B,CACtD,OAAAC,EAAO,gBAAgB,WAAY,MAAQD,EAAK,MAAM,GAAG,CAAC,EAEnDI,EAAW,KAAKJ,EAAM,SAAY,CACvC,GAAI,CACF,OAAOF,EAAW,MAAMD,EAAUG,EAAM,CAAC,SAAU,QAAS,KAAM,GAAG,CAAC,CAAC,CACzE,OACOE,EAAK,CACV,MAAAD,EAAO,MAAM,WAAY,mBAAoB,CAAC,KAAAD,CAAI,EAAGE,CAAG,EAClD,IAAI,MAAM,mBAAoB,CAAC,MAAQA,EAAc,KAAK,CAAC,CACnE,CACF,CAAC,CACH,CCrDA,OAAQ,iBAAiBG,EAAgB,cAAAC,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AW,cAcnB,eAAsBC,GAAcC,EAA6B,CAC/D,OAAAC,EAAO,gBAAgB,gBAAiB,MAAQD,EAAK,MAAM,GAAG,CAAC,GACvD,MAAMF,EAAKE,EAAM,GAAG,GAAG,MAAM,CACvC,CCXA,OAAQ,WAAAE,OAAc,OACtB,OAAQ,cAAAC,OAAiB,KACzB,OAAQ,UAAAC,OAAa",
6
+ "names": ["AsyncQueue", "definePackage", "logger", "asyncQueue", "readFileSync_", "readFile_", "flatString", "readFileSync", "path", "logger", "err", "readFile", "asyncQueue", "writeFileSync_", "existsSync", "mkdirSync", "renameSync", "mkdir", "rename", "writeFile_", "dirname", "writeFileSync", "path", "content", "logger", "pathExists", "dir", "err", "writeFile", "asyncQueue", "parseJson", "content", "err", "logger", "jsonStringify", "data", "readJson", "path", "sync", "logger", "parseJson", "readFileSync", "readFile", "content", "flatString", "writeJson", "path", "data", "sync", "logger", "content", "jsonStringify", "writeFileSync", "writeFile", "open", "makeEmptyFile", "path", "logger", "resolve", "existsSync", "unlink"]
7
+ }
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Make empty file.
3
+ *
4
+ * @param path - file path
5
+ *
6
+ * @example
7
+ * ```ts
8
+ * await makeFile('./file.txt');
9
+ * ```
10
+ */
11
+ export declare function makeEmptyFile(path: string): Promise<void>;
12
+ //# sourceMappingURL=make-file.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"make-file.d.ts","sourceRoot":"","sources":["../src/make-file.ts"],"names":[],"mappings":"AAIA;;;;;;;;;GASG;AACH,wBAAsB,aAAa,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAG/D"}
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Enhanced read File (Synchronous).
3
+ *
4
+ * @param path - file path
5
+ * @returns file content
6
+ * @example
7
+ * ```typescript
8
+ * const fileContent = readFileSync('./file.txt', sync);
9
+ * ```
10
+ */
11
+ export declare function readFileSync(path: string): string;
12
+ /**
13
+ * Enhanced read File (Asynchronous).
14
+ *
15
+ * - If writing queue is running for target path, it will wait for it to finish.
16
+ *
17
+ * @param path - file path
18
+ * @returns file content
19
+ * @example
20
+ * ```typescript
21
+ * const fileContent = await readFile('./file.txt', sync);
22
+ * ```
23
+ */
24
+ export declare function readFile(path: string): Promise<string>;
25
+ //# sourceMappingURL=read-file.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"read-file.d.ts","sourceRoot":"","sources":["../src/read-file.ts"],"names":[],"mappings":"AAOA;;;;;;;;;GASG;AACH,wBAAgB,YAAY,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAUjD;AAED;;;;;;;;;;;GAWG;AACH,wBAAgB,QAAQ,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAYtD"}
@@ -0,0 +1,37 @@
1
+ import type { Dictionary, MaybePromise } from '@alwatr/type-helper';
2
+ /**
3
+ * Enhanced read json file (async).
4
+ *
5
+ * @param path - file path
6
+ * @returns json object
7
+ * @example
8
+ * ```typescript
9
+ * const fileContent = await readJson('./file.json');
10
+ * ```
11
+ */
12
+ export declare function readJson<T extends Dictionary>(path: string): Promise<T>;
13
+ /**
14
+ * Enhanced read json file (sync).
15
+ *
16
+ * @param path - file path
17
+ * @param sync - sync mode
18
+ * @returns json object
19
+ * @example
20
+ * ```typescript
21
+ * const fileContent = readJson('./file.json', true);
22
+ * ```
23
+ */
24
+ export declare function readJson<T extends Dictionary>(path: string, sync: true): T;
25
+ /**
26
+ * Enhanced read json file.
27
+ *
28
+ * @param path - file path
29
+ * @param sync - sync mode
30
+ * @returns json object
31
+ * @example
32
+ * ```typescript
33
+ * const fileContent = await readJson('./file.json', sync);
34
+ * ```
35
+ */
36
+ export declare function readJson<T extends Dictionary>(path: string, sync: boolean): MaybePromise<T>;
37
+ //# sourceMappingURL=read-json.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"read-json.d.ts","sourceRoot":"","sources":["../src/read-json.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAC,UAAU,EAAE,YAAY,EAAC,MAAM,qBAAqB,CAAC;AAElE;;;;;;;;;GASG;AACH,wBAAgB,QAAQ,CAAC,CAAC,SAAS,UAAU,EAAE,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC;AACzE;;;;;;;;;;GAUG;AACH,wBAAgB,QAAQ,CAAC,CAAC,SAAS,UAAU,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,IAAI,GAAG,CAAC,CAAC;AAC5E;;;;;;;;;;GAUG;AACH,wBAAgB,QAAQ,CAAC,CAAC,SAAS,UAAU,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,OAAO,GAAG,YAAY,CAAC,CAAC,CAAC,CAAC"}
@@ -0,0 +1,33 @@
1
+ /**
2
+ * Enhanced write file (Synchronous).
3
+ *
4
+ * - If directory not exists, create it recursively.
5
+ * - Write file to `path.tmp` before write success.
6
+ * - If file exists, renamed (keep) to `path.bak`.
7
+ * - If write failed, original file will not be changed.
8
+ *
9
+ * @param path - file path
10
+ * @param content - file content
11
+ * @example
12
+ * ```typescript
13
+ * writeFileSync('./file.txt', 'Hello World!');
14
+ * ```
15
+ */
16
+ export declare function writeFileSync(path: string, content: string): void;
17
+ /**
18
+ * Enhanced write file (Asynchronous).
19
+ *
20
+ * - If directory not exists, create it recursively.
21
+ * - Write file to `path.tmp` before write success.
22
+ * - If file exists, renamed (keep) to `path.bak`.
23
+ * - If write failed, original file will not be changed.
24
+ *
25
+ * @param path - file path
26
+ * @param content - file content
27
+ * @example
28
+ * ```typescript
29
+ * await writeFile('./file.txt', 'Hello World!');
30
+ * ```
31
+ */
32
+ export declare function writeFile(path: string, content: string): Promise<void>;
33
+ //# sourceMappingURL=write-file.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"write-file.d.ts","sourceRoot":"","sources":["../src/write-file.ts"],"names":[],"mappings":"AAMA;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,aAAa,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,IAAI,CAqBjE;AAED;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,SAAS,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAwBtE"}
@@ -0,0 +1,37 @@
1
+ import type { Dictionary, MaybePromise } from '@alwatr/type-helper';
2
+ /**
3
+ * Enhanced write json file (Asynchronous).
4
+ *
5
+ * @param path - file path
6
+ * @param data - json object
7
+ * @example
8
+ * ```typescript
9
+ * await writeJsonFile('./file.json', { a:1, b:2, c:3 });
10
+ * ```
11
+ */
12
+ export declare function writeJson<T extends Dictionary>(path: string, data: T, sync?: false): Promise<void>;
13
+ /**
14
+ * Enhanced write json file (Synchronous).
15
+ *
16
+ * @param path - file path
17
+ * @param data - json object
18
+ * @param sync - sync mode
19
+ * @example
20
+ * ```typescript
21
+ * writeJsonFile('./file.json', { a:1, b:2, c:3 }, true);
22
+ * ```
23
+ */
24
+ export declare function writeJson<T extends Dictionary>(path: string, data: T, sync: true): void;
25
+ /**
26
+ * Enhanced write json file.
27
+ *
28
+ * @param path - file path
29
+ * @param data - json object
30
+ * @param sync - sync mode
31
+ * @example
32
+ * ```typescript
33
+ * await writeJsonFile('./file.json', { a:1, b:2, c:3 }, sync);
34
+ * ```
35
+ */
36
+ export declare function writeJson<T extends Dictionary>(path: string, data: T, sync: boolean): MaybePromise<void>;
37
+ //# sourceMappingURL=write-json.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"write-json.d.ts","sourceRoot":"","sources":["../src/write-json.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAC,UAAU,EAAE,YAAY,EAAC,MAAM,qBAAqB,CAAC;AAElE;;;;;;;;;GASG;AACH,wBAAgB,SAAS,CAAC,CAAC,SAAS,UAAU,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC,EAAE,IAAI,CAAC,EAAE,KAAK,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;AACpG;;;;;;;;;;GAUG;AACH,wBAAgB,SAAS,CAAC,CAAC,SAAS,UAAU,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC,EAAE,IAAI,EAAE,IAAI,GAAG,IAAI,CAAC;AACzF;;;;;;;;;;GAUG;AACH,wBAAgB,SAAS,CAAC,CAAC,SAAS,UAAU,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC,EAAE,IAAI,EAAE,OAAO,GAAG,YAAY,CAAC,IAAI,CAAC,CAAC"}
package/package.json ADDED
@@ -0,0 +1,89 @@
1
+ {
2
+ "name": "@alwatr/node-fs",
3
+ "version": "1.0.0-beta.0",
4
+ "description": "Enhanced file system operations in Node.js with asynchronous queue to prevent parallel writes.",
5
+ "author": "S. Ali Mihandoost <ali.mihandoost@gmail.com>",
6
+ "keywords": [
7
+ "node-fs",
8
+ "fs",
9
+ "file",
10
+ "filesystem",
11
+ "readFile",
12
+ "writeFile",
13
+ "readJson",
14
+ "writeJson",
15
+ "JSON",
16
+ "async",
17
+ "queue",
18
+ "cross-platform",
19
+ "ECMAScript",
20
+ "typescript",
21
+ "javascript",
22
+ "node",
23
+ "nodejs",
24
+ "esm",
25
+ "module",
26
+ "utility",
27
+ "util",
28
+ "utils",
29
+ "nanolib",
30
+ "alwatr"
31
+ ],
32
+ "type": "module",
33
+ "main": "./dist/main.cjs",
34
+ "module": "./dist/main.mjs",
35
+ "types": "./dist/main.d.ts",
36
+ "exports": {
37
+ ".": {
38
+ "import": "./dist/main.mjs",
39
+ "require": "./dist/main.cjs",
40
+ "types": "./dist/main.d.ts"
41
+ }
42
+ },
43
+ "license": "MIT",
44
+ "files": [
45
+ "**/*.{js,mjs,cjs,map,d.ts,html,md}",
46
+ "!demo/**/*"
47
+ ],
48
+ "publishConfig": {
49
+ "access": "public"
50
+ },
51
+ "repository": {
52
+ "type": "git",
53
+ "url": "https://github.com/Alwatr/nanolib",
54
+ "directory": "packages/node-fs"
55
+ },
56
+ "homepage": "https://github.com/Alwatr/nanolib/tree/next/packages/node-fs#readme",
57
+ "bugs": {
58
+ "url": "https://github.com/Alwatr/nanolib/issues"
59
+ },
60
+ "prettier": "@alwatr/prettier-config",
61
+ "scripts": {
62
+ "b": "yarn run build",
63
+ "w": "yarn run watch",
64
+ "c": "yarn run clean",
65
+ "cb": "yarn run clean && yarn run build",
66
+ "d": "yarn run build:es && yarn node --enable-source-maps --trace-warnings",
67
+ "build": "yarn run build:ts & yarn run build:es",
68
+ "build:es": "nano-build --preset=module",
69
+ "build:ts": "tsc --build",
70
+ "watch": "yarn run watch:ts & yarn run watch:es",
71
+ "watch:es": "yarn run build:es --watch",
72
+ "watch:ts": "yarn run build:ts --watch --preserveWatchOutput",
73
+ "clean": "rm -rfv dist *.tsbuildinfo"
74
+ },
75
+ "dependencies": {
76
+ "@alwatr/async-queue": "^1.1.0",
77
+ "@alwatr/flat-string": "^1.0.12",
78
+ "@alwatr/logger": "^3.2.1"
79
+ },
80
+ "devDependencies": {
81
+ "@alwatr/nano-build": "^1.3.0",
82
+ "@alwatr/prettier-config": "^1.0.4",
83
+ "@alwatr/tsconfig-base": "^1.1.0",
84
+ "@alwatr/type-helper": "^1.0.3",
85
+ "@types/node": "^20.10.7",
86
+ "typescript": "^5.3.3"
87
+ },
88
+ "gitHead": "51edc127640bdfd74834e98d2d09de6f16564a8d"
89
+ }