nuxt-file-storage 0.2.8 → 0.3.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 CHANGED
@@ -1,21 +1,21 @@
1
- MIT License
2
-
3
- Copyright (c) 2024-Present Nuxt File Storage Project
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
1
+ MIT License
2
+
3
+ Copyright (c) 2024-Present Nuxt File Storage Project
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
21
  SOFTWARE.
package/README.md CHANGED
@@ -1,165 +1,193 @@
1
- ![Nuxt File Storage Banner](./playground/public/nuxt-file-storage-banner.svg)
2
-
3
- # Nuxt File Storage
4
-
5
- [![Visits Badge](https://badges.pufler.dev/visits/nyllre/nuxt-file-storage)](https://badges.pufler.dev)
6
- [![npm version][npm-version-src]][npm-version-href]
7
- [![npm downloads][npm-downloads-src]][npm-downloads-href]
8
- [![License][license-src]][license-href]
9
- [![Nuxt][nuxt-src]][nuxt-href]
10
-
11
- Easy solution to store files in your nuxt apps. Be able to upload files from the frontend and recieve them from the backend to then save the files in your project.
12
-
13
- - [✨  Release Notes](/CHANGELOG.md)
14
- - [🏀 Online playground](https://stackblitz.com/github/NyllRE/nuxt-file-storage?file=playground%2Fapp.vue)
15
- <!-- - [📖 &nbsp;Documentation](https://example.com) -->
16
-
17
- ## Features
18
-
19
- <!-- Highlight some of the features your module provide here -->
20
-
21
- - 📁 &nbsp;Get files from file input and make them ready to send to backend
22
- - ⚗️ &nbsp;Serialize files in the backend to be able to use them appropriately
23
- - 🖴 &nbsp;Store files in a specified location in your Nuxt backend with Nitro Engine
24
-
25
- ## Quick Setup
26
-
27
- 1. Add `nuxt-file-storage` dependency to your project
28
-
29
- ```bash
30
- # Using pnpm
31
- pnpm add -D nuxt-file-storage
32
-
33
- # Using yarn
34
- yarn add --dev nuxt-file-storage
35
-
36
- # Using npm
37
- npm install --save-dev nuxt-file-storage
38
- ```
39
-
40
- 2. Add `nuxt-file-storage` to the `modules` section of `nuxt.config.ts`
41
-
42
- ```js
43
- export default defineNuxtConfig({
44
- modules: ['nuxt-file-storage'],
45
- })
46
- ```
47
-
48
- That's it! You can now use Nuxt Storage in your Nuxt app ✨
49
-
50
- ## Configuration
51
-
52
- You can currently configure a single setting of the `nuxt-file-storage` module. Here is the config interface:
53
-
54
- ```js
55
- export default defineNuxtConfig({
56
- modules: ['nuxt-file-storage'],
57
- fileStorage: {
58
- // enter the absolute path to the location of your storage
59
- mount: '/home/$USR/development/nuxt-file-storage/server/files',
60
-
61
- // {OR} use environment variables (recommended)
62
- mount: process.env.mount
63
- // you need to set the mount in your .env file at the root of your project
64
- },
65
- })
66
- ```
67
-
68
- ## Usage
69
-
70
- ### Handling Files in the frontend
71
- You can use Nuxt Storage to get the files from the `<input>` tag:
72
-
73
- ```html
74
- <template>
75
- <input type="file" @input="handleFileInput" />
76
- </template>
77
-
78
- <script setup>
79
- // handleFileInput can handle multiple files
80
- const { handleFileInput, files } = useFileStorage()
81
- </script>
82
- ```
83
- The `files` return a ref object that contains the files
84
-
85
- > `handleFileInput` returns a promise in case you need to check if the file input has concluded
86
-
87
-
88
- Here's an example of using files to send them to the backend:
89
- ```html
90
- <template>
91
- <input type="file" @input="handleFileInput" />
92
- <button @click="submit">submit</button>
93
- </template>
94
-
95
- <script setup>
96
- const { handleFileInput, files } = useFileStorage()
97
-
98
- const submit = async () => {
99
- const response = await $fetch('/api/files', {
100
- method: 'POST',
101
- body: {
102
- files: files.value
103
- }
104
- })
105
- }
106
- </script>
107
- ```
108
-
109
-
110
- ### Handling files in the backend
111
- using Nitro Server Engine, we will make an api route that recieves the files and stores them in the folder `userFiles`
112
- ```ts
113
- export default defineEventHandler(async (event) => {
114
- const { files } = await readBody<{ files: File[] }>(event)
115
-
116
- for ( const file of files ) {
117
- await storeFileLocally(
118
- file, // the file object
119
- 8, // you can add a name for the file or length of Unique ID that will be automatically generated!
120
- '/userFiles' // the folder the file will be stored in
121
- )
122
-
123
- // {OR}
124
-
125
- // Parses a data URL and returns an object with the binary data and the file extension.
126
- const { binaryString, ext } = parseDataUrl(file.content)
127
- }
128
-
129
- return 'success!'
130
- })
131
-
132
- interface File {
133
- name: string
134
- content: string
135
- }
136
- ```
137
-
138
- And that's it! Now you can store any file in your nuxt project from the user ✨
139
-
140
- ## Contribution
141
- Run into a problem? Open a [new issue](https://github.com/NyllRE/nuxt-file-storage/issues/new). I'll try my best to include all the features requested if it is fitting to the scope of the project.
142
-
143
- Want to add some feature? PRs are welcome!
144
- - Clone this repository
145
- - install the dependencies
146
- - prepare the project
147
- - run dev server
148
- ```bash
149
- git clone https://github.com/NyllRE/nuxt-file-storage && cd nuxt-file-storage
150
- npm i
151
- npm run dev:prepare
152
- npm run dev
153
- ```
154
-
155
-
156
- <!-- Badges -->
157
-
158
- [npm-version-src]: https://img.shields.io/npm/v/nuxt-file-storage/latest.svg?style=flat&colorA=18181B&colorB=28CF8D
159
- [npm-version-href]: https://npmjs.com/package/nuxt-file-storage
160
- [npm-downloads-src]: https://img.shields.io/npm/dm/nuxt-file-storage.svg?style=flat&colorA=18181B&colorB=28CF8D
161
- [npm-downloads-href]: https://npmjs.com/package/nuxt-file-storage
162
- [license-src]: https://img.shields.io/npm/l/nuxt-file-storage.svg?style=flat&colorA=18181B&colorB=28CF8D
163
- [license-href]: https://npmjs.com/package/nuxt-file-storage
164
- [nuxt-src]: https://img.shields.io/badge/Nuxt-18181B?logo=nuxt.js
165
- [nuxt-href]: https://nuxt.com/modules/nuxt-file-storage
1
+ ![Nuxt File Storage Banner](./playground/public/nuxt-file-storage-banner.svg)
2
+
3
+ # Nuxt File Storage
4
+
5
+ [![Visits Badge](https://badges.pufler.dev/visits/nyllre/nuxt-file-storage)](https://badges.pufler.dev)
6
+ [![npm version][npm-version-src]][npm-version-href]
7
+ [![npm downloads][npm-downloads-src]][npm-downloads-href]
8
+ [![License][license-src]][license-href]
9
+ [![Nuxt][nuxt-src]][nuxt-href]
10
+
11
+ Easy solution to store files in your nuxt apps. Be able to upload files from the frontend and receive them from the backend to then save the files in your project.
12
+
13
+ - [✨ &nbsp;Release Notes](/CHANGELOG.md)
14
+ - [🏀 Online playground](https://stackblitz.com/github/NyllRE/nuxt-file-storage?file=playground%2Fapp.vue)
15
+ <!-- - [📖 &nbsp;Documentation](https://example.com) -->
16
+
17
+ ## Features
18
+
19
+ <!-- Highlight some of the features your module provide here -->
20
+
21
+ - 📁 &nbsp;Get files from file input and make them ready to send to backend
22
+ - ⚗️ &nbsp;Serialize files in the backend to be able to use them appropriately
23
+ - 🖴 &nbsp;Store files in a specified location in your Nuxt backend with Nitro Engine
24
+
25
+ ## Quick Setup
26
+
27
+ 1. Add `nuxt-file-storage` dependency to your project
28
+
29
+ ```bash
30
+ # Using pnpm
31
+ pnpm add -D nuxt-file-storage
32
+
33
+ # Using yarn
34
+ yarn add --dev nuxt-file-storage
35
+
36
+ # Using npm
37
+ npm install --save-dev nuxt-file-storage
38
+ ```
39
+
40
+ 2. Add `nuxt-file-storage` to the `modules` section of `nuxt.config.ts`
41
+
42
+ ```js
43
+ export default defineNuxtConfig({
44
+ modules: ['nuxt-file-storage'],
45
+ })
46
+ ```
47
+
48
+ That's it! You can now use Nuxt Storage in your Nuxt app ✨
49
+
50
+ ## Configuration
51
+
52
+ You can currently configure a single setting of the `nuxt-file-storage` module. Here is the config interface:
53
+
54
+ ```js
55
+ export default defineNuxtConfig({
56
+ modules: ['nuxt-file-storage'],
57
+ fileStorage: {
58
+ // enter the absolute path to the location of your storage
59
+ mount: '/home/$USR/development/nuxt-file-storage/server/files',
60
+
61
+ // {OR} use environment variables (recommended)
62
+ mount: process.env.mount
63
+ // you need to set the mount in your .env file at the root of your project
64
+ },
65
+ })
66
+ ```
67
+
68
+ ## Usage
69
+
70
+ ### Handling Files in the frontend
71
+ You can use Nuxt Storage to get the files from the `<input>` tag:
72
+
73
+ ```html
74
+ <template>
75
+ <input type="file" @input="handleFileInput" />
76
+ </template>
77
+
78
+ <script setup>
79
+ // handleFileInput can handle multiple files
80
+ // clearOldFiles: true by default, each time the user adds files the `files` ref will be cleared
81
+ const { handleFileInput, files } = useFileStorage({ clearOldFiles: false })
82
+ </script>
83
+ ```
84
+ The `files` return a ref object that contains the files
85
+
86
+ > `handleFileInput` returns a promise in case you need to check if the file input has concluded
87
+
88
+ <br>
89
+
90
+ Here's an example of using files to send them to the backend
91
+ ```html
92
+ <template>
93
+ <input type="file" @input="handleFileInput" />
94
+ <button @click="submit">submit</button>
95
+ </template>
96
+
97
+ <script setup>
98
+ const { handleFileInput, files } = useFileStorage()
99
+
100
+ const submit = async () => {
101
+ const response = await $fetch('/api/files', {
102
+ method: 'POST',
103
+ body: {
104
+ files: files.value
105
+ }
106
+ })
107
+ }
108
+ </script>
109
+ ```
110
+ <br>
111
+
112
+ #### Handling multiple file input fields
113
+ You have to create a new instance of `useFileStorage` for each input field
114
+
115
+
116
+ ```html
117
+ <template>
118
+ <input type="file" @input="handleFileInput" multiple /> ← | 1 |
119
+ <input type="file" @input="profileInputHandler" /> ← | 2 |
120
+ </template>
121
+
122
+ <script setup>
123
+ const { handleFileInput, files } = useFileStorage() ← | 1 |
124
+
125
+ const {
126
+ handleFileInput: profileInputHandler,
127
+ files: profileImage
128
+ } = useFileStorage() ← | 2 |
129
+ </script>
130
+ ```
131
+ by calling a new `useFileStorage` instance you separate the internal logic between the inputs
132
+
133
+ ### Handling files in the backend
134
+ using Nitro Server Engine, we will make an api route that receives the files and stores them in the folder `userFiles`
135
+ ```ts
136
+ import { ServerFile } from "nuxt-file-storage";
137
+
138
+ export default defineEventHandler(async (event) => {
139
+ const { files } = await readBody<{ files: ServerFile[] }>(event)
140
+
141
+ for ( const file of files ) {
142
+ await storeFileLocally(
143
+ file, // the file object
144
+ 8, // you can add a name for the file or length of Unique ID that will be automatically generated!
145
+ '/userFiles' // the folder the file will be stored in
146
+ )
147
+
148
+ // {OR}
149
+
150
+ // Parses a data URL and returns an object with the binary data and the file extension.
151
+ const { binaryString, ext } = parseDataUrl(file.content)
152
+ }
153
+
154
+ // Deleting Files
155
+ await deleteFile('requiredFile.txt', '/userFiles')
156
+
157
+ // Get file path
158
+ await getFileLocally('requiredFile.txt', '/userFiles')
159
+ // returns: {AbsolutePath}/userFiles/requiredFile.txt
160
+
161
+ // Get all files in a folder
162
+ await getFilesLocally('/userFiles')
163
+ })
164
+ ```
165
+
166
+ And that's it! Now you can store any file in your nuxt project from the user ✨
167
+
168
+ ## Contribution
169
+ Run into a problem? Open a [new issue](https://github.com/NyllRE/nuxt-file-storage/issues/new). I'll try my best to include all the features requested if it is fitting to the scope of the project.
170
+
171
+ Want to add some feature? PRs are welcome!
172
+ - Clone this repository
173
+ - install the dependencies
174
+ - prepare the project
175
+ - run dev server
176
+ ```bash
177
+ git clone https://github.com/NyllRE/nuxt-file-storage && cd nuxt-file-storage
178
+ npm i
179
+ npm run dev:prepare
180
+ npm run dev
181
+ ```
182
+
183
+
184
+ <!-- Badges -->
185
+
186
+ [npm-version-src]: https://img.shields.io/npm/v/nuxt-file-storage/latest.svg?style=flat&colorA=18181B&colorB=28CF8D
187
+ [npm-version-href]: https://npmjs.com/package/nuxt-file-storage
188
+ [npm-downloads-src]: https://img.shields.io/npm/dm/nuxt-file-storage.svg?style=flat&colorA=18181B&colorB=28CF8D
189
+ [npm-downloads-href]: https://npmjs.com/package/nuxt-file-storage
190
+ [license-src]: https://img.shields.io/npm/l/nuxt-file-storage.svg?style=flat&colorA=18181B&colorB=28CF8D
191
+ [license-href]: https://npmjs.com/package/nuxt-file-storage
192
+ [nuxt-src]: https://img.shields.io/badge/Nuxt-18181B?logo=nuxt.js
193
+ [nuxt-href]: https://nuxt.com/modules/nuxt-file-storage
package/dist/module.d.mts CHANGED
@@ -1,9 +1,24 @@
1
1
  import * as _nuxt_schema from '@nuxt/schema';
2
2
 
3
- interface ModuleOptions {
4
- mount: string;
5
- version: string;
3
+ interface ServerFile {
4
+ name: string
5
+ content: string
6
+ size: string
7
+ type: string
8
+ lastModified: string
9
+ }
10
+
11
+ interface ClientFile extends Blob {
12
+ content: string | ArrayBuffer | null | undefined
13
+ name: string
14
+ lastModified: number
15
+ }
16
+
17
+ interface ModuleOptions {
18
+ mount: string
19
+ version: string
6
20
  }
7
- declare const _default: _nuxt_schema.NuxtModule<ModuleOptions>;
8
21
 
9
- export { type ModuleOptions, _default as default };
22
+ declare const _default: _nuxt_schema.NuxtModule<ModuleOptions, ModuleOptions, false>;
23
+
24
+ export { type ClientFile, type ModuleOptions, type ServerFile, _default as default };
package/dist/module.d.ts CHANGED
@@ -1,9 +1,24 @@
1
1
  import * as _nuxt_schema from '@nuxt/schema';
2
2
 
3
- interface ModuleOptions {
4
- mount: string;
5
- version: string;
3
+ interface ServerFile {
4
+ name: string
5
+ content: string
6
+ size: string
7
+ type: string
8
+ lastModified: string
9
+ }
10
+
11
+ interface ClientFile extends Blob {
12
+ content: string | ArrayBuffer | null | undefined
13
+ name: string
14
+ lastModified: number
15
+ }
16
+
17
+ interface ModuleOptions {
18
+ mount: string
19
+ version: string
6
20
  }
7
- declare const _default: _nuxt_schema.NuxtModule<ModuleOptions>;
8
21
 
9
- export { type ModuleOptions, _default as default };
22
+ declare const _default: _nuxt_schema.NuxtModule<ModuleOptions, ModuleOptions, false>;
23
+
24
+ export { type ClientFile, type ModuleOptions, type ServerFile, _default as default };
package/dist/module.json CHANGED
@@ -1,5 +1,9 @@
1
1
  {
2
2
  "name": "nuxt-file-storage",
3
3
  "configKey": "fileStorage",
4
- "version": "0.2.8"
4
+ "version": "0.3.0",
5
+ "builder": {
6
+ "@nuxt/module-builder": "0.8.4",
7
+ "unbuild": "2.0.0"
8
+ }
5
9
  }
package/dist/module.mjs CHANGED
@@ -1,8 +1,6 @@
1
1
  import { defineNuxtModule, logger, createResolver, addImportsDir, addServerScanDir } from '@nuxt/kit';
2
2
  import defu from 'defu';
3
3
 
4
- const version = "0.2.8";
5
-
6
4
  const module = defineNuxtModule({
7
5
  meta: {
8
6
  name: "nuxt-file-storage",
@@ -18,17 +16,14 @@ const module = defineNuxtModule({
18
16
  config.public.fileStorage = defu(config.public.fileStorage, {
19
17
  ...options
20
18
  });
21
- if (nuxt.options.dev) {
22
- //! I couldn't find a way to detect new updates to warn one time so it will warn every time the server runs again, if you know how to warn about a breaking change only the first run after an update feel free to open a new pull request
23
- const previousVersion = config.public.fileStorage?.version;
24
- if (!previousVersion || previousVersion !== version) {
25
- logger.warn(
26
- `There is a breaking change in the \`storeFileLocally\` method, link to changelog:
27
- https://github.com/NyllRE/nuxt-file-storage/releases/tag/v${version}
28
- `
29
- );
30
- config.public.fileStorage.version = version;
31
- }
19
+ if (!config.public.fileStorage.mount) {
20
+ logger.error(
21
+ "Please provide a mount path for the file storage module in your nuxt.config.js"
22
+ );
23
+ } else {
24
+ logger.ready(
25
+ `Nuxt File Storage has mounted successfully`
26
+ );
32
27
  }
33
28
  const resolve = createResolver(import.meta.url).resolve;
34
29
  addImportsDir(resolve("runtime/composables"));
@@ -1,4 +1,38 @@
1
- export default function (): {
2
- files: import("vue").Ref<any[]>;
1
+ import type { ClientFile } from '../../types.js';
2
+ type Options = {
3
+ clearOldFiles: boolean;
4
+ };
5
+ export default function (options?: Options): {
6
+ files: import("vue").Ref<{
7
+ content: string | {
8
+ readonly byteLength: number;
9
+ slice: (begin: number, end?: number | undefined) => ArrayBuffer;
10
+ readonly [Symbol.toStringTag]: string;
11
+ } | null | undefined;
12
+ name: string;
13
+ lastModified: number;
14
+ readonly size: number;
15
+ readonly type: string;
16
+ arrayBuffer: () => Promise<ArrayBuffer>;
17
+ slice: (start?: number | undefined, end?: number | undefined, contentType?: string | undefined) => Blob;
18
+ stream: () => ReadableStream<Uint8Array>;
19
+ text: () => Promise<string>;
20
+ }[], ClientFile[] | {
21
+ content: string | {
22
+ readonly byteLength: number;
23
+ slice: (begin: number, end?: number | undefined) => ArrayBuffer;
24
+ readonly [Symbol.toStringTag]: string;
25
+ } | null | undefined;
26
+ name: string;
27
+ lastModified: number;
28
+ readonly size: number;
29
+ readonly type: string;
30
+ arrayBuffer: () => Promise<ArrayBuffer>;
31
+ slice: (start?: number | undefined, end?: number | undefined, contentType?: string | undefined) => Blob;
32
+ stream: () => ReadableStream<Uint8Array>;
33
+ text: () => Promise<string>;
34
+ }[]>;
3
35
  handleFileInput: (event: any) => Promise<void>;
36
+ clearFiles: () => void;
4
37
  };
38
+ export {};
@@ -1,5 +1,5 @@
1
1
  import { ref } from "vue";
2
- export default function() {
2
+ export default function(options = { clearOldFiles: true }) {
3
3
  const files = ref([]);
4
4
  const serializeFile = (file) => {
5
5
  return new Promise((resolve, reject) => {
@@ -21,8 +21,13 @@ export default function() {
21
21
  reader.readAsDataURL(file);
22
22
  });
23
23
  };
24
+ const clearFiles = () => {
25
+ files.value.splice(0, files.value.length);
26
+ };
24
27
  const handleFileInput = async (event) => {
25
- files.value.splice(0);
28
+ if (options.clearOldFiles) {
29
+ clearFiles();
30
+ }
26
31
  const promises = [];
27
32
  for (const file of event.target.files) {
28
33
  promises.push(serializeFile(file));
@@ -31,6 +36,7 @@ export default function() {
31
36
  };
32
37
  return {
33
38
  files,
34
- handleFileInput
39
+ handleFileInput,
40
+ clearFiles
35
41
  };
36
42
  }
@@ -1,17 +1,58 @@
1
1
  /// <reference types="node" />
2
+ /// <reference types="node" />
3
+ import type { ServerFile } from '../../../types.js';
2
4
  /**
3
- * #### Will store the file in the specified directory
5
+ * @description Will store the file in the specified directory
6
+ * @param file provide the file object
7
+ * @param fileNameOrIdLength you can pass a string or a number, if you enter a string it will be the file name, if you enter a number it will generate a unique ID
8
+ * @param filelocation provide the folder you wish to locate the file in
4
9
  * @returns file name: `${filename}`.`${fileExtension}`
5
- * @prop file: provide the file object
6
- * @prop fileNameOrIdLength: you can pass a string or a number, if you enter a string it will be the file name, if you enter a number it will generate a unique ID
7
- * @prop filelocation: provide the folder you wish to locate the file in
10
+ *
11
+ *
12
+ * [Documentation](https://github.com/NyllRE/nuxt-file-storage#handling-files-in-the-backend)
13
+ *
14
+ *
15
+ * @example
16
+ * ```ts
17
+ * import { ServerFile } from "nuxt-file-storage";
18
+ *
19
+ * const { file } = await readBody<{ files: ServerFile }>(event)
20
+
21
+ * await storeFileLocally( file, 8, '/userFiles' )
22
+ * ```
8
23
  */
9
24
  export declare const storeFileLocally: (file: ServerFile, fileNameOrIdLength: string | number, filelocation?: string) => Promise<string>;
25
+ /**
26
+ * @description Get file path in the specified directory
27
+ * @param filename provide the file name (return of storeFileLocally)
28
+ * @param filelocation provide the folder you wish to locate the file in
29
+ * @returns file path: `${config.fileStorage.mount}/${filelocation}/${filename}`
30
+ */
31
+ export declare const getFileLocally: (filename: string, filelocation?: string) => string;
32
+ /**
33
+ * @description Get all files in the specified directory
34
+ * @param filelocation provide the folder you wish to locate the file in
35
+ * @returns all files in filelocation: `${config.fileStorage.mount}/${filelocation}`
36
+ */
37
+ export declare const getFilesLocally: (filelocation?: string) => Promise<string[]>;
38
+ /**
39
+ * @param filename the name of the file you want to delete
40
+ * @param filelocation the folder where the file is located, if it is in the root folder you can leave it empty, if it is in a subfolder you can pass the name of the subfolder with a preceding slash: `/subfolder`
41
+ * @example
42
+ * ```ts
43
+ * await deleteFile('/userFiles', 'requiredFile.txt')
44
+ * ```
45
+ */
10
46
  export declare const deleteFile: (filename: string, filelocation?: string) => Promise<void>;
11
47
  /**
12
- Parses a data URL and returns an object with the binary data and the file extension.
13
- @param {string} file - The data URL
14
- @returns {{ binaryString: Buffer, ext: string }} - An object with the binary data and the file extension
48
+ * @description Parses a data URL and returns an object with the binary data and the file extension.
49
+ * @param {string} file - The data URL
50
+ * @returns {{binaryString: Buffer, ext: string}} An object with the binary data - file extension
51
+ *
52
+ * @example
53
+ * ```ts
54
+ * const { binaryString, ext } = parseDataUrl(file.content)
55
+ * ```
15
56
  */
16
57
  export declare const parseDataUrl: (file: string) => {
17
58
  binaryString: Buffer;
@@ -1,19 +1,31 @@
1
- import { writeFile, rm, mkdir } from "fs/promises";
1
+ import { writeFile, rm, mkdir, readdir } from "fs/promises";
2
2
  import { useRuntimeConfig } from "#imports";
3
+ import { join } from "path";
3
4
  export const storeFileLocally = async (file, fileNameOrIdLength, filelocation = "") => {
4
5
  const { binaryString, ext } = parseDataUrl(file.content);
5
6
  const location = useRuntimeConfig().public.fileStorage.mount;
6
7
  const originalExt = file.name.toString().split(".").pop() || ext;
7
8
  const filename = typeof fileNameOrIdLength == "number" ? `${generateRandomId(fileNameOrIdLength)}.${originalExt}` : `${fileNameOrIdLength}.${originalExt}`;
8
- await mkdir(`${location}${filelocation}`, { recursive: true });
9
- await writeFile(`${location}${filelocation}/${filename}`, binaryString, {
9
+ await mkdir(join(location, filelocation), { recursive: true });
10
+ await writeFile(join(location, filelocation, filename), binaryString, {
10
11
  flag: "w"
11
12
  });
12
13
  return filename;
13
14
  };
15
+ export const getFileLocally = (filename, filelocation = "") => {
16
+ const location = useRuntimeConfig().public.fileStorage.mount;
17
+ const normalizedFilelocation = filelocation.startsWith("/") ? filelocation.slice(1) : filelocation;
18
+ return join(location, normalizedFilelocation, filename);
19
+ };
20
+ export const getFilesLocally = async (filelocation = "") => {
21
+ const location = useRuntimeConfig().public.fileStorage.mount;
22
+ const normalizedFilelocation = filelocation.startsWith("/") ? filelocation.slice(1) : filelocation;
23
+ return await readdir(join(location, normalizedFilelocation)).catch(() => []);
24
+ };
14
25
  export const deleteFile = async (filename, filelocation = "") => {
15
26
  const location = useRuntimeConfig().public.fileStorage.mount;
16
- await rm(`${location}${filelocation}/${filename}`);
27
+ const normalizedFilelocation = filelocation.startsWith("/") ? filelocation.slice(1) : filelocation;
28
+ await rm(join(location, normalizedFilelocation, filename));
17
29
  };
18
30
  const generateRandomId = (length) => {
19
31
  const characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
package/dist/types.d.mts CHANGED
@@ -1,16 +1 @@
1
-
2
- import type { ModuleOptions } from './module.js'
3
-
4
-
5
- declare module '@nuxt/schema' {
6
- interface NuxtConfig { ['fileStorage']?: Partial<ModuleOptions> }
7
- interface NuxtOptions { ['fileStorage']?: ModuleOptions }
8
- }
9
-
10
- declare module 'nuxt/schema' {
11
- interface NuxtConfig { ['fileStorage']?: Partial<ModuleOptions> }
12
- interface NuxtOptions { ['fileStorage']?: ModuleOptions }
13
- }
14
-
15
-
16
- export type { ModuleOptions, default } from './module.js'
1
+ export { type ClientFile, type ModuleOptions, type ServerFile, default } from './module.js'
package/dist/types.d.ts CHANGED
@@ -1,16 +1 @@
1
-
2
- import type { ModuleOptions } from './module'
3
-
4
-
5
- declare module '@nuxt/schema' {
6
- interface NuxtConfig { ['fileStorage']?: Partial<ModuleOptions> }
7
- interface NuxtOptions { ['fileStorage']?: ModuleOptions }
8
- }
9
-
10
- declare module 'nuxt/schema' {
11
- interface NuxtConfig { ['fileStorage']?: Partial<ModuleOptions> }
12
- interface NuxtOptions { ['fileStorage']?: ModuleOptions }
13
- }
14
-
15
-
16
- export type { ModuleOptions, default } from './module'
1
+ export { type ClientFile, type ModuleOptions, type ServerFile, default } from './module'
package/package.json CHANGED
@@ -1,46 +1,46 @@
1
1
  {
2
- "name": "nuxt-file-storage",
3
- "version": "0.2.8",
4
- "description": "Easy solution to store files in your nuxt apps. Be able to upload files from the frontend and recieve them from the backend to then save the files in your project.",
5
- "repository": "NyllRE/nuxt-file-storage",
6
- "license": "MIT",
7
- "type": "module",
8
- "exports": {
9
- ".": {
10
- "types": "./dist/types.d.ts",
11
- "import": "./dist/module.mjs",
12
- "require": "./dist/module.cjs"
13
- }
14
- },
15
- "main": "./dist/module.cjs",
16
- "types": "./dist/types.d.ts",
17
- "files": [
18
- "dist"
19
- ],
20
- "scripts": {
21
- "prepack": "nuxt-module-build build",
22
- "dev": "nuxi dev playground",
23
- "dev:build": "nuxi build playground",
24
- "dev:prepare": "nuxt-module-build build --stub && nuxt-module-build prepare && nuxi prepare playground",
25
- "release": "npm run lint && npm run test && npm run prepack && changelogen --release && npm publish && git push --follow-tags",
26
- "lint": "eslint .",
27
- "test": "vitest run",
28
- "test:watch": "vitest watch"
29
- },
30
- "dependencies": {
31
- "@nuxt/kit": "^3.9.3",
32
- "defu": "^6.1.4"
33
- },
34
- "devDependencies": {
35
- "@nuxt/devtools": "latest",
36
- "@nuxt/eslint-config": "^0.2.0",
37
- "@nuxt/module-builder": "^0.8.3",
38
- "@nuxt/schema": "^3.9.3",
39
- "@nuxt/test-utils": "^3.9.0",
40
- "@types/node": "^20.11.5",
41
- "changelogen": "^0.5.5",
42
- "eslint": "^8.56.0",
43
- "nuxt": "^3.9.3",
44
- "vitest": "^1.0.0"
45
- }
46
- }
2
+ "name": "nuxt-file-storage",
3
+ "version": "0.3.0",
4
+ "description": "Easy solution to store files in your nuxt apps. Be able to upload files from the frontend and recieve them from the backend to then save the files in your project.",
5
+ "repository": "NyllRE/nuxt-file-storage",
6
+ "license": "MIT",
7
+ "type": "module",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/types.d.ts",
11
+ "import": "./dist/module.mjs",
12
+ "require": "./dist/module.cjs"
13
+ }
14
+ },
15
+ "main": "./dist/module.cjs",
16
+ "types": "./dist/types.d.ts",
17
+ "files": [
18
+ "dist"
19
+ ],
20
+ "scripts": {
21
+ "prepack": "nuxt-module-build build",
22
+ "dev": "nuxi dev playground",
23
+ "dev:build": "nuxi build playground",
24
+ "dev:prepare": "nuxt-module-build build --stub && nuxt-module-build prepare && nuxi prepare playground",
25
+ "release": "npm run lint && npm run prepack && changelogen && npm publish && git push --follow-tags",
26
+ "lint": "eslint .",
27
+ "test": "vitest run",
28
+ "test:watch": "vitest watch"
29
+ },
30
+ "dependencies": {
31
+ "@nuxt/kit": "^3.15.4",
32
+ "defu": "^6.1.4"
33
+ },
34
+ "devDependencies": {
35
+ "@nuxt/devtools": "latest",
36
+ "@nuxt/eslint-config": "^0.2.0",
37
+ "@nuxt/module-builder": "^0.8.4",
38
+ "@nuxt/schema": "^3.15.4",
39
+ "@nuxt/test-utils": "^3.17.0",
40
+ "@types/node": "^20.17.19",
41
+ "changelogen": "^0.5.7",
42
+ "eslint": "^8.57.1",
43
+ "nuxt": "^3.15.4",
44
+ "vitest": "^1.6.1"
45
+ }
46
+ }
File without changes