@stonyx/utils 0.0.3 → 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/package.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "keywords": [
4
4
  "stonyx-module"
5
5
  ],
6
- "version": "0.0.3",
6
+ "version": "0.1.0",
7
7
  "description": "Utils module for Stonyx Framework",
8
8
  "type": "module",
9
9
  "exports": {
package/src/file.js CHANGED
@@ -1,23 +1,24 @@
1
1
  import { getTimestamp } from '@stonyx/utils/date';
2
2
  import { kebabCaseToCamelCase } from '@stonyx/utils/string';
3
+ import { objToJson } from '@stonyx/utils/object';
3
4
  import { promises as fsp } from 'fs';
4
5
  import path from 'path';
5
6
 
6
- export async function createFile(filePath, data) {
7
+ export async function createFile(filePath, data, { json }) {
7
8
  try {
8
- await fsp.writeFile(filePath, data, 'utf8');
9
+ await fsp.writeFile(filePath, json ? objToJson(data) : data, 'utf8');
9
10
  } catch (error) {
10
11
  throw new Error(error);
11
12
  }
12
13
  }
13
14
 
14
- export async function updateFile(filePath, data) {
15
+ export async function updateFile(filePath, data, { json }) {
15
16
  try {
16
17
  await fsp.access(filePath);
17
18
 
18
19
  const swapFile = `${filePath}.temp-${getTimestamp()}`;
19
- await fsp.writeFile(swapFile, data);
20
- await fsp.rename(swapFile, file);
20
+ await fsp.writeFile(swapFile, json ? objToJson(data) : data);
21
+ await fsp.rename(swapFile, filePath);
21
22
  } catch (error) {
22
23
 
23
24
  throw new Error(error);
@@ -34,15 +35,23 @@ export async function readFile(filePath, { json, missingFileCallback }) {
34
35
  return json ? JSON.parse(fileData) : fileData;
35
36
  } catch (error) {
36
37
  if (error.code === 'ENOENT' && missingFileCallback) {
37
- missingFileCallback(filePath);
38
- return;
38
+ return missingFileCallback(filePath);
39
39
  }
40
40
 
41
41
  throw new Error(error);
42
42
  }
43
43
  }
44
44
 
45
- export async function deleteFile(filePath) {
45
+ export async function deleteFile(filePath, options) {
46
+ try {
47
+ filePath = path.resolve(filePath);
48
+
49
+ await fsp.access(filePath);
50
+ } catch (error) {
51
+ if (options?.ignoreAccessFailure) return;
52
+ throw error;
53
+ }
54
+
46
55
  await fsp.unlink(filePath);
47
56
  }
48
57
 
package/src/object.js CHANGED
@@ -2,6 +2,10 @@ export function deepCopy(obj) {
2
2
  return JSON.parse(JSON.stringify(obj));
3
3
  }
4
4
 
5
+ export function objToJson(obj) {
6
+ return JSON.stringify(obj);
7
+ }
8
+
5
9
  export function mergeObject(obj1, obj2) {
6
10
  if (Array.isArray(obj1) || Array.isArray(obj2)) throw new Error('Cannot merge arrays.');
7
11
  if (typeof obj1 !== 'object' || obj1 === null) return structuredClone(obj2);