basic-node-server 1.0.15 → 1.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.
Files changed (6) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +66 -39
  3. package/bns.js +238 -153
  4. package/index.html +49 -49
  5. package/mime.json +1203 -1203
  6. package/package.json +20 -20
package/LICENSE CHANGED
@@ -1,21 +1,21 @@
1
- MIT License
2
-
3
- Copyright (c) 2024 Skapi
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.
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Skapi
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 CHANGED
@@ -1,39 +1,66 @@
1
- # basic-node-server
2
- Basic node server for everyone.
3
-
4
- Basic node server simply hosts and serves files from the current project directory through HTTP.
5
- If no path is given, or if the path ends with '/' or '\', it will serve the index.html file in the directory.
6
-
7
- ## Installation
8
-
9
- ```
10
- npm install basic-node-server
11
- ```
12
-
13
- ## Usage
14
-
15
- Then, you can run it from your project directory:
16
-
17
- ```
18
- npx bns [port] 404=[404.page]
19
- ```
20
-
21
- The [port] argument is optional. If no port is given, it will default to 3000.
22
-
23
- For example, if you want to serve the current directory on port 8080, you would run:
24
-
25
- ```
26
- npx bns 8080
27
- ```
28
-
29
- If you need to setup additional 404 page you can do so by:
30
-
31
- ```
32
- npx bns 8080 404=your404page.html
33
- ```
34
-
35
- If you need to set response header to have no-caching settings:
36
-
37
- ```
38
- npx bns 8080 404=your404page.html no-cache=true
39
- ```
1
+ # basic-node-server
2
+
3
+ A small static file server for local hosting and quick testing.
4
+
5
+ It serves files from your current working directory over HTTP.
6
+
7
+ - If the request path is `/` (or ends with `/`), it serves `index.html`.
8
+ - It only serves files inside the current directory.
9
+ - It supports conditional caching via `ETag` and `Last-Modified` (`304 Not Modified`).
10
+
11
+ ## Installation
12
+
13
+ ```bash
14
+ npm install basic-node-server
15
+ ```
16
+
17
+ ## Quick Start
18
+
19
+ ```bash
20
+ npx bns
21
+ ```
22
+
23
+ Default port is `3000`.
24
+
25
+ ## Usage
26
+
27
+ ```bash
28
+ npx bns [port=<number>] [404=<file>] [no-cache=true]
29
+ ```
30
+
31
+ Show CLI help:
32
+
33
+ ```bash
34
+ npx bns --help
35
+ ```
36
+
37
+ ## Options
38
+
39
+ - `port=<number>`: Optional port number (`1-65535`), defaults to `3000`.
40
+ - `404=<file>`: Optional custom 404 page (must be inside current directory).
41
+ - `no-cache=true`: Adds no-cache headers (`Cache-Control`, `Pragma`, `Expires`).
42
+
43
+ ## Examples
44
+
45
+ ```bash
46
+ # Serve current directory on port 3000
47
+ npx bns
48
+
49
+ # Serve on port 8080
50
+ npx bns port=8080
51
+
52
+ # Use a custom 404 page
53
+ npx bns port=8080 404=404.html
54
+
55
+ # Disable caching headers
56
+ npx bns no-cache=true port=8080
57
+
58
+ # Custom 404 + no-cache
59
+ npx bns 404=404.html no-cache=true port=8080
60
+ ```
61
+
62
+ ## Request Behavior
63
+
64
+ - Supported methods: `GET`, `HEAD`
65
+ - Unsupported methods return `405 Method Not Allowed`
66
+ - Missing files return `404` (or custom 404 file if configured)
package/bns.js CHANGED
@@ -1,153 +1,238 @@
1
- #!/usr/bin/env node
2
-
3
- const http = require('http');
4
- const fs = require('fs');
5
- const path = require('path');
6
-
7
- let port = process.argv[2] || 3000; // Set the port from the command line argument or default to 3000
8
- try{
9
- port = parseInt(port);
10
- if (isNaN(port) || port < 1 || port > 65535) {
11
- console.log('Invalid port number. Falling back to default port 3000.');
12
- port = 3000;
13
- }
14
- }
15
- catch (error) {
16
- console.log('Invalid port number. Falling back to default port 3000.');
17
- port = 3000;
18
- }
19
-
20
- let notFoundFile = null;
21
- let noCache = false;
22
-
23
- // loop through the arguments from index 3
24
- for (let i = 2; i < process.argv.length; i++) {
25
- if (process.argv[i].startsWith('404=')) {
26
- notFoundFile = notFoundFile.split('=').slice(1).join('=');
27
- }
28
- else if (process.argv[i] === 'no-cache=true') {
29
- noCache = true;
30
- }
31
- // else if it's a file name
32
- else if (process.argv[i].endsWith('.html') || process.argv[i].endsWith('.htm') || process.argv[i].endsWith('.txt')) {
33
- notFoundFile = process.argv[i];
34
- }
35
- }
36
-
37
- const mimeJson = path.join(__dirname, '/mime.json');
38
-
39
- const getContentType = (() => {
40
- return new Promise((resolve, reject) => {
41
- fs.readFile(mimeJson, 'utf8', (err, data) => {
42
- if (err) {
43
- reject(err);
44
- }
45
- else {
46
- resolve(JSON.parse(data));
47
- }
48
- });
49
- })
50
- })();
51
-
52
- function setNoCache(res) {
53
- res.setNoCache('Cache-Control', 'no-cache, no-store, must-revalidate');
54
- res.setNoCache('Pragma', 'no-cache');
55
- res.setNoCache('Expires', '0');
56
- return res;
57
- }
58
-
59
- const server = http.createServer((req, res) => {
60
- // Extract the file path from the request URL
61
- let filePath = path.join(process.cwd(), req.url);
62
-
63
- // check if its a get request
64
- if (req.method !== 'GET') {
65
- res.statusCode = 405;
66
- res.end('Method not allowed');
67
- }
68
-
69
- // remove get query string
70
- filePath = filePath.split('?')[0];
71
-
72
- // If filePath is empty or ends with '/', default to 'index.html'
73
- if (!filePath || filePath.endsWith('/') || filePath.endsWith('\\')) {
74
- filePath = path.join(filePath, 'index.html');
75
- }
76
-
77
- // Check if the file exists
78
- fs.access(filePath, fs.constants.F_OK, (err) => {
79
- if (err) {
80
- // File not found
81
- if (notFoundFile) {
82
- filePath = path.join(process.cwd(), notFoundFile);
83
- fs.access(filePath, fs.constants.F_OK, (err) => {
84
- if (err) {
85
- res.statusCode = 404;
86
- res.end('File not found');
87
- } else {
88
- // Read the file and send it as the response
89
- const fileExtension = path.extname(filePath).substring(1);
90
- getContentType.then(contentType => {
91
- console.log(`Serving: ${filePath}`);
92
-
93
- contentType = contentType[fileExtension] || 'application/octet-stream';
94
- res.setHeader('Content-Type', contentType);
95
-
96
- fs.readFile(filePath, (err, data) => {
97
- if (err) {
98
- // Error reading the file
99
- res.statusCode = 500;
100
- res.end('Internal server error');
101
- } else {
102
- // Send the file contents as the response
103
- res.statusCode = 200;
104
- res.end(data);
105
- }
106
- });
107
- });
108
- }
109
- });
110
- }
111
- else {
112
- res.statusCode = 404;
113
- res.end('File not found');
114
- }
115
- } else {
116
- // Read the file and send it as the response
117
- const fileExtension = path.extname(filePath).substring(1);
118
- getContentType.then(contentType => {
119
- console.log(`Serving: ${filePath}`);
120
-
121
- contentType = contentType[fileExtension] || 'application/octet-stream';
122
- res.setHeader('Content-Type', contentType);
123
-
124
- fs.readFile(filePath, (err, data) => {
125
- if (err) {
126
- // Error reading the file
127
- res.statusCode = 500;
128
- res.end('Internal server error');
129
- } else {
130
- // Send the file contents as the response
131
- res.statusCode = 200;
132
- // set no-cache header if noCache is true
133
- if (noCache) {
134
- setNoCache(res);
135
- }
136
- res.end(data);
137
- }
138
- });
139
- });
140
- }
141
- });
142
- });
143
-
144
- server.listen(port, () => {
145
- console.log(`Server running on port ${port}`);
146
- console.log(`404 file: ${notFoundFile}`);
147
- console.log(`No cache: ${noCache}`);
148
- console.log(`Serving files from: ${process.cwd()}`);
149
- console.log(`Use Ctrl+C to stop the server`);
150
- console.log(`Use 'bns.js <port> 404=<file>' to set a custom 404 file`);
151
- console.log(`Use 'bns.js <port> no-cache=true' to set no-cache headers`);
152
- console.log(`Use 'bns.js <port> 404=<file> no-cache=true' to set a custom 404 file and no-cache headers`);
153
- });
1
+ #!/usr/bin/env node
2
+
3
+ const http = require('http');
4
+ const fs = require('fs');
5
+ const path = require('path');
6
+ const rootDir = process.cwd();
7
+ const contentTypes = require('./mime.json');
8
+
9
+ const args = process.argv.slice(2);
10
+
11
+ function printHelp() {
12
+ console.log('Basic Node Server');
13
+ console.log('Usage:');
14
+ console.log('- npx bns [port=<number>] [404=<file>] [no-cache=true]');
15
+ console.log('');
16
+ console.log('Options:');
17
+ console.log('- port=<number>: Optional port number (1-65535), defaults to 3000');
18
+ console.log('- 404=<file>: Optional custom 404 file path (inside current directory)');
19
+ console.log('- no-cache=true: Optional no-cache response headers');
20
+ console.log('- -h, --help: Show this help and exit');
21
+ console.log('');
22
+ console.log('Examples:');
23
+ console.log('- npx bns');
24
+ console.log('- npx bns port=8080');
25
+ console.log('- npx bns 404=notfound.html port=8080');
26
+ console.log('- npx bns no-cache=true port=8080');
27
+ console.log('- npx bns 404=notfound.html no-cache=true port=8080');
28
+ }
29
+
30
+ if (args.includes('-h') || args.includes('--help')) {
31
+ printHelp();
32
+ process.exit(0);
33
+ }
34
+
35
+ let port = 3000;
36
+ let notFoundFile = null;
37
+ let noCache = false;
38
+
39
+ for (const arg of args) {
40
+ if (arg.startsWith('port=')) {
41
+ const rawPort = arg.slice(5);
42
+ const parsedPort = parseInt(rawPort, 10);
43
+ if (/^\d+$/.test(rawPort) && parsedPort >= 1 && parsedPort <= 65535) {
44
+ port = parsedPort;
45
+ } else {
46
+ console.log('Invalid port value in port=<number>. Falling back to default port 3000.');
47
+ port = 3000;
48
+ }
49
+ } else if (arg.startsWith('404=')) {
50
+ notFoundFile = arg.slice(4);
51
+ } else if (arg === 'no-cache=true') {
52
+ noCache = true;
53
+ } else if (arg === 'no-cache=false') {
54
+ noCache = false;
55
+ } else if (arg.endsWith('.html') || arg.endsWith('.htm') || arg.endsWith('.txt')) {
56
+ notFoundFile = arg;
57
+ }
58
+ }
59
+
60
+ function isWithinRoot(targetPath) {
61
+ const relativePath = path.relative(rootDir, targetPath);
62
+ return relativePath === '' || (!relativePath.startsWith('..') && !path.isAbsolute(relativePath));
63
+ }
64
+
65
+ function resolveLocalPath(inputPath) {
66
+ const resolvedPath = path.resolve(rootDir, inputPath);
67
+ if (!isWithinRoot(resolvedPath)) {
68
+ return null;
69
+ }
70
+ return resolvedPath;
71
+ }
72
+
73
+ let notFoundFilePath = null;
74
+ if (notFoundFile) {
75
+ notFoundFilePath = resolveLocalPath(notFoundFile);
76
+ if (!notFoundFilePath) {
77
+ console.log('Invalid 404 file path (outside current directory). Ignoring custom 404 file.');
78
+ notFoundFile = null;
79
+ }
80
+ }
81
+
82
+ function setNoCache(res) {
83
+ res.setHeader('Cache-Control', 'no-cache, no-store, must-revalidate');
84
+ res.setHeader('Pragma', 'no-cache');
85
+ res.setHeader('Expires', '0');
86
+ }
87
+
88
+ function setDefaultCache(res) {
89
+ res.setHeader('Cache-Control', 'public, max-age=0, must-revalidate');
90
+ }
91
+
92
+ function buildEtag(stat) {
93
+ return `W/"${stat.size.toString(16)}-${Math.floor(stat.mtimeMs).toString(16)}"`;
94
+ }
95
+
96
+ function setCacheValidators(res, stat) {
97
+ res.setHeader('ETag', buildEtag(stat));
98
+ res.setHeader('Last-Modified', stat.mtime.toUTCString());
99
+ if (!noCache) {
100
+ setDefaultCache(res);
101
+ }
102
+ }
103
+
104
+ function shouldReturnNotModified(req, stat) {
105
+ const ifNoneMatch = req.headers['if-none-match'];
106
+ const etag = buildEtag(stat);
107
+
108
+ if (ifNoneMatch) {
109
+ const candidates = ifNoneMatch
110
+ .split(',')
111
+ .map(value => value.trim());
112
+ if (candidates.includes('*') || candidates.includes(etag)) {
113
+ return true;
114
+ }
115
+ }
116
+
117
+ const ifModifiedSince = req.headers['if-modified-since'];
118
+ if (!ifModifiedSince) {
119
+ return false;
120
+ }
121
+
122
+ const modifiedSince = Date.parse(ifModifiedSince);
123
+ if (Number.isNaN(modifiedSince)) {
124
+ return false;
125
+ }
126
+
127
+ return Math.floor(stat.mtimeMs / 1000) * 1000 <= modifiedSince;
128
+ }
129
+
130
+ function sendResponse(res, statusCode, contentType, body, isHead) {
131
+ res.statusCode = statusCode;
132
+ if (contentType) {
133
+ res.setHeader('Content-Type', contentType);
134
+ }
135
+ if (noCache) {
136
+ setNoCache(res);
137
+ }
138
+ if (isHead) {
139
+ res.end();
140
+ return;
141
+ }
142
+ res.end(body);
143
+ }
144
+
145
+ function getContentType(filePath) {
146
+ const extension = path.extname(filePath).substring(1).toLowerCase();
147
+ return contentTypes[extension] || 'application/octet-stream';
148
+ }
149
+
150
+ function resolveRequestPath(requestUrl) {
151
+ const rawPath = requestUrl.split('?')[0] || '/';
152
+ let decodedPath;
153
+
154
+ try {
155
+ decodedPath = decodeURIComponent(rawPath);
156
+ } catch (error) {
157
+ return null;
158
+ }
159
+
160
+ let normalizedPath = decodedPath;
161
+ if (normalizedPath.endsWith('/') || normalizedPath.endsWith('\\')) {
162
+ normalizedPath = `${normalizedPath}index.html`;
163
+ }
164
+
165
+ return resolveLocalPath(`.${normalizedPath}`);
166
+ }
167
+
168
+ async function serveFile(req, res, filePath, statusCode, isHead) {
169
+ const stat = await fs.promises.stat(filePath);
170
+ if (!stat.isFile()) {
171
+ const error = new Error('Not a file');
172
+ error.code = 'ENOENT';
173
+ throw error;
174
+ }
175
+
176
+ const contentType = getContentType(filePath);
177
+ setCacheValidators(res, stat);
178
+
179
+ if (shouldReturnNotModified(req, stat)) {
180
+ sendResponse(res, 304, contentType, null, true);
181
+ return;
182
+ }
183
+
184
+ const data = isHead ? null : await fs.promises.readFile(filePath);
185
+ sendResponse(res, statusCode, contentType, data, isHead);
186
+ }
187
+
188
+ const server = http.createServer(async (req, res) => {
189
+ const isHead = req.method === 'HEAD';
190
+ if (req.method !== 'GET' && !isHead) {
191
+ res.setHeader('Allow', 'GET, HEAD');
192
+ sendResponse(res, 405, 'text/plain; charset=utf-8', 'Method not allowed', false);
193
+ return;
194
+ }
195
+
196
+ const requestFilePath = resolveRequestPath(req.url);
197
+ if (!requestFilePath) {
198
+ sendResponse(res, 400, 'text/plain; charset=utf-8', 'Bad request', isHead);
199
+ return;
200
+ }
201
+
202
+ try {
203
+ console.log(`Serving: ${requestFilePath}`);
204
+ await serveFile(req, res, requestFilePath, 200, isHead);
205
+ } catch (error) {
206
+ if (error.code === 'ENOENT' || error.code === 'EISDIR') {
207
+ if (notFoundFilePath) {
208
+ try {
209
+ console.log(`Serving 404 file: ${notFoundFilePath}`);
210
+ await serveFile(req, res, notFoundFilePath, 404, isHead);
211
+ return;
212
+ } catch (notFoundError) {
213
+ // Fallback below if custom 404 file can't be read.
214
+ }
215
+ }
216
+ sendResponse(res, 404, 'text/plain; charset=utf-8', 'File not found', isHead);
217
+ return;
218
+ }
219
+
220
+ sendResponse(res, 500, 'text/plain; charset=utf-8', 'Internal server error', isHead);
221
+ }
222
+ });
223
+
224
+ server.listen(port, () => {
225
+ console.log('Basic Node Server is running');
226
+ console.log(`- Port: ${port}`);
227
+ console.log(`- Root: ${rootDir}`);
228
+ console.log(`- Custom 404: ${notFoundFile || 'none'}`);
229
+ console.log(`- No-cache headers: ${noCache}`);
230
+ console.log('');
231
+ console.log('Quick commands:');
232
+ console.log('- Stop server: Ctrl+C');
233
+ console.log('- Help: npx bns --help');
234
+ console.log('- Set port: npx bns port=8080');
235
+ console.log('- Custom 404: npx bns port=8080 404=notfound.html');
236
+ console.log('- Disable caching: npx bns port=8080 no-cache=true');
237
+ console.log('- Custom 404 + no-cache: npx bns port=8080 404=notfound.html no-cache=true');
238
+ });
package/index.html CHANGED
@@ -1,50 +1,50 @@
1
- <!DOCTYPE html>
2
-
3
- <h1>Basic Node Server</h1>
4
-
5
- <p>
6
- Basic node server for everyone.
7
- <br>
8
- Basic node server simply hosts and serves files from the current project directory through HTTP.
9
- <br>
10
- If no path is given, it will serve the index.html file.
11
- </p>
12
-
13
- <h2>How to use</h2>
14
- <pre>
15
- node bns [port] 404=[404 file] no-cache=[true]
16
- </pre>
17
- <p>
18
- The [port] argument is optional. If no port is given, it will default to 3000.
19
- <br>
20
- For example, if you want to serve the current directory on port 8080, you would run:
21
- </p>
22
- <pre>
23
- node bns 8080
24
- </pre>
25
- <p>
26
- The 404=[404 file] argument is optional. If file location is given, it will respond the file on 404.
27
- <br>
28
- For example, if you want your 404 page to be 404.html on port 8080, you would run:
29
- </p>
30
- <pre>
31
- node bns 8080 404=404.html
32
- </pre>
33
- <p>
34
- The no-cache=[true] argument is optional. If no-cache option is given, it will respond with no-cache headers.
35
- <br>
36
- For example, if you want to prevent your page from being cached, you would run:
37
- </p>
38
- <pre>
39
- node bns no-cache=true
40
- </pre>
41
- <h2>NPM</h2>
42
- <pre>
43
- npm install basic-node-server
44
- </pre>
45
- <p>
46
- Then, you can run it from your project directory:
47
- </p>
48
- <pre>
49
- npx bns [port] 404=[404 file] no-cache=[true]
1
+ <!DOCTYPE html>
2
+
3
+ <h1>Basic Node Server</h1>
4
+
5
+ <p>
6
+ Basic node server for everyone.
7
+ <br>
8
+ Basic node server simply hosts and serves files from the current project directory through HTTP.
9
+ <br>
10
+ If no path is given, it will serve the index.html file.
11
+ </p>
12
+
13
+ <h2>How to use</h2>
14
+ <pre>
15
+ node bns [port] 404=[404 file] no-cache=[true]
16
+ </pre>
17
+ <p>
18
+ The [port] argument is optional. If no port is given, it will default to 3000.
19
+ <br>
20
+ For example, if you want to serve the current directory on port 8080, you would run:
21
+ </p>
22
+ <pre>
23
+ node bns 8080
24
+ </pre>
25
+ <p>
26
+ The 404=[404 file] argument is optional. If file location is given, it will respond the file on 404.
27
+ <br>
28
+ For example, if you want your 404 page to be 404.html on port 8080, you would run:
29
+ </p>
30
+ <pre>
31
+ node bns 8080 404=404.html
32
+ </pre>
33
+ <p>
34
+ The no-cache=[true] argument is optional. If no-cache option is given, it will respond with no-cache headers.
35
+ <br>
36
+ For example, if you want to prevent your page from being cached, you would run:
37
+ </p>
38
+ <pre>
39
+ node bns no-cache=true
40
+ </pre>
41
+ <h2>NPM</h2>
42
+ <pre>
43
+ npm install basic-node-server
44
+ </pre>
45
+ <p>
46
+ Then, you can run it from your project directory:
47
+ </p>
48
+ <pre>
49
+ npx bns [port] 404=[404 file] no-cache=[true]
50
50
  </pre>