cli-ns 1.0.1 → 1.0.3

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/app.js ADDED
@@ -0,0 +1,228 @@
1
+ #!/usr/bin/env node
2
+ import http from "http";
3
+ import url from "url";
4
+ import path from "path";
5
+ import fs from "fs";
6
+ import httpProxy from 'http-proxy';
7
+ import { fileURLToPath } from 'url';
8
+
9
+ const __filename = fileURLToPath(import.meta.url);
10
+ const __dirname = path.dirname(__filename);
11
+
12
+ const VERSION = "1.0.1";
13
+ const CONFIG_FILE = "cli-ns.json";
14
+
15
+ function showHelp() {
16
+ console.log(`\n cli-ns - Simple Static Web Server CLI\n`);
17
+ console.log(` Usage:\n`);
18
+ console.log(` cli-ns [port] Start server on specified port (default: 9999)`);
19
+ console.log(` cli-ns -v, --version Show version`);
20
+ console.log(` cli-ns -h, --help Show this help message`);
21
+ console.log(` cli-ns -init Generate ${CONFIG_FILE} configuration file\n`);
22
+ console.log(` Examples:\n`);
23
+ console.log(` cli-ns Start server on port 9999`);
24
+ console.log(` cli-ns 8080 Start server on port 8080`);
25
+ console.log(` cli-ns -init Generate configuration file\n`);
26
+ }
27
+
28
+ function showVersion() {
29
+ console.log(`cli-ns v${VERSION}`);
30
+ }
31
+
32
+ function generateConfigFile() {
33
+ const defaultConfig = {
34
+ port: 8080,
35
+ staticDir: "./static",
36
+ proxy: {
37
+ "/api": {
38
+ target: "http://localhost:3000"
39
+ }
40
+ }
41
+ };
42
+
43
+ const configPath = path.join(process.cwd(), CONFIG_FILE);
44
+
45
+ if (fs.existsSync(configPath)) {
46
+ console.log(`\n ${CONFIG_FILE} already exists in current directory.\n`);
47
+ process.exit(0);
48
+ }
49
+
50
+ fs.writeFileSync(configPath, JSON.stringify(defaultConfig, null, 4));
51
+ console.log(`\n ${CONFIG_FILE} has been created in current directory.\n`);
52
+ console.log(` You can edit this file to customize your server configuration.\n`);
53
+ process.exit(0);
54
+ }
55
+
56
+ function loadConfigFile() {
57
+ const configPath = path.join(process.cwd(), CONFIG_FILE);
58
+ if (fs.existsSync(configPath)) {
59
+ try {
60
+ const configContent = fs.readFileSync(configPath, 'utf-8');
61
+ return JSON.parse(configContent);
62
+ } catch (error) {
63
+ console.log(`\n Warning: Failed to parse ${CONFIG_FILE}, using default configuration.\n`);
64
+ return null;
65
+ }
66
+ }
67
+ return null;
68
+ }
69
+
70
+ const args = process.argv.slice(2);
71
+
72
+ if (args[0] === "-v" || args[0] === "--version") {
73
+ showVersion();
74
+ process.exit(0);
75
+ }
76
+
77
+ if (args[0] === "-h" || args[0] === "--help") {
78
+ showHelp();
79
+ process.exit(0);
80
+ }
81
+
82
+ if (args[0] === "-init" || args[0] === "--init") {
83
+ generateConfigFile();
84
+ }
85
+
86
+ const configFile = loadConfigFile();
87
+
88
+ let port = 9999;
89
+ if (args.length && !isNaN(args[0])) {
90
+ port = parseInt(args[0]);
91
+ }
92
+
93
+ let staticPath = path.join(__dirname, "public");
94
+ let proxyConfig = [];
95
+
96
+ if (configFile) {
97
+ if (configFile.port) {
98
+ port = configFile.port;
99
+ }
100
+ if (configFile.staticDir) {
101
+ staticPath = path.resolve(process.cwd(), configFile.staticDir);
102
+ }
103
+ if (configFile.proxy) {
104
+ proxyConfig = Object.entries(configFile.proxy).map(([path, target]) => ({
105
+ path,
106
+ target: typeof target === 'string' ? target : target.target
107
+ }));
108
+ }
109
+ }
110
+
111
+ const config = {
112
+ staticPath,
113
+ listen_port: port,
114
+ proxy: proxyConfig,
115
+ defaultFile: ["index.html", "index.htm", "default.htm", "default.html", "home.html"],
116
+ gzip: true,
117
+ cacheSecond: 172800,
118
+ isHistory: true,
119
+ contentType: {
120
+ csv: "text/csv",
121
+ css: "text/css",
122
+ gif: "image/gif",
123
+ html: "text/html",
124
+ ico: "image/x-icon",
125
+ jpeg: "image/jpeg",
126
+ jpg: "image/jpeg",
127
+ js: "text/javascript",
128
+ json: "application/json",
129
+ pdf: "application/pdf",
130
+ png: "image/png",
131
+ svg: "image/svg+xml",
132
+ swf: "application/x-shockwave-flash",
133
+ tiff: "image/tiff",
134
+ txt: "text/plain",
135
+ wav: "audio/x-wav",
136
+ wma: "audio/x-ms-wma",
137
+ wmv: "video/x-ms-wmv",
138
+ xml: "text/xml",
139
+ },
140
+ };
141
+
142
+
143
+ const etag = 'df551425fcc55e4d42a1487' + new Date().getTime();
144
+ const proxy = httpProxy.createProxyServer({});
145
+ const app = http
146
+ .createServer(function (request, response) {
147
+ var pathName = url.parse(request.url).pathname;
148
+ var extName = path.extname(pathName).toLowerCase(); // .js
149
+ var fullPath = config.staticPath + pathName;
150
+ var extName2 = extName.replace(".", "");
151
+ if (!extName && pathName.slice(-1) != "/") {
152
+ pathName += "/";
153
+ }
154
+ console.log("pathName", pathName, "extName", extName, "fullPath", fullPath);
155
+ if (config.proxy && config.proxy.length) {
156
+ for (const p of config.proxy) {
157
+ if (pathName.indexOf(p.path) == 0) {
158
+ proxy.web(request, response, {
159
+ target: p.target,
160
+ changeOrigin: true
161
+ });
162
+ console.log(pathName, "=proxy=>", p.target + pathName);
163
+ return;
164
+ }
165
+ }
166
+ }
167
+
168
+ if (!extName) {
169
+ var isfix = false;
170
+ for (var i = 0; i < config.defaultFile.length; i++) {
171
+ if (fs.existsSync(fullPath + config.defaultFile[i])) {
172
+ fullPath = fullPath + config.defaultFile[i];
173
+ isfix = true;
174
+ break;
175
+ }
176
+ }
177
+ if (!isfix) {
178
+ fullPath = fullPath + config.defaultFile[0];
179
+ }
180
+ }
181
+
182
+ console.log(fullPath);
183
+ if (!fs.existsSync(fullPath)) {
184
+ if (config.isHistory) {
185
+ pathName = "/index.html";
186
+ fullPath = config.staticPath + pathName;
187
+ } else {
188
+ response.writeHead(400, { "Content-Type": "text/html" });
189
+ response.end("<h1>404 not found<br />File " + pathName + " not found.<h1>");
190
+ return;
191
+ }
192
+ }
193
+ fs.readFile(fullPath, "binary", function (err, file) {
194
+ if (err) {
195
+ response.writeHead(500, {
196
+ "Content-Type": "text/plain",
197
+ });
198
+ response.end(err.toString());
199
+ } else {
200
+ var _contentType = "text/html";
201
+ if (extName2 && config.contentType[extName2]) {
202
+ _contentType = config.contentType[extName2];
203
+ }
204
+ const header = {
205
+ "Content-Type": _contentType,
206
+ };
207
+ // 增加允许跨域
208
+ header["Access-Control-Allow-Credentials"] = "true";
209
+ header["Access-Control-Allow-Origin"] = "*";
210
+ header["Access-Control-Allow-Headers"] = "X-Requested-With";
211
+ header["Access-Control-Allow-Methods"] = "PUT,POST,GET,DELETE,OPTIONS";
212
+ if (config.cacheSecond && ['.js', '.css', '.png', '.jpg', '.jpeg', '.bmp', '.webp', '.svg', '.gif', '.ico', '.exif', '.ai', '.apng', '.avif', '.woff2'].includes(extName)) {
213
+ header['Cache-Control'] = 'public, max-age=' + config.cacheSecond;
214
+ header['Expires'] = new Date(Date.now() + (config.cacheSecond * 1000)).toUTCString();
215
+ header['ETag'] = etag;
216
+ }
217
+ response.writeHead(200, header);
218
+ response.write(file, "binary");
219
+ response.end();
220
+ }
221
+ });
222
+ })
223
+ .listen(config.listen_port);
224
+ app.timeout = 36000000;
225
+
226
+ console.log(`\n cli-ns v${VERSION}`);
227
+ console.log(` Static server running at http://localhost:${config.listen_port}/`);
228
+ console.log(` Serving files from: ${config.staticPath}\n`);
package/cli-ns.json ADDED
@@ -0,0 +1,9 @@
1
+ {
2
+ "port": 8081,
3
+ "staticDir": "./static",
4
+ "proxy": {
5
+ "/api": {
6
+ "target": "http://localhost:3000"
7
+ }
8
+ }
9
+ }
package/package.json CHANGED
@@ -1,11 +1,11 @@
1
1
  {
2
2
  "name": "cli-ns",
3
- "version": "1.0.1",
3
+ "version": "1.0.3",
4
4
  "description": "node.js开发的简单的静态文件服务器",
5
5
  "main": "app.js",
6
6
  "scripts": {
7
- "start": "node ./src/app.js",
8
- "build": "esbuild ./src/app.js --bundle --minify --outfile=./bin/app.js --platform=node"
7
+ "start": "node ./app.js",
8
+ "test":"cli-ns -v"
9
9
  },
10
10
  "type": "module",
11
11
  "repository": {
@@ -13,13 +13,17 @@
13
13
  "url": "https://gitee.com/chen-binfa/mini-static-webserver.git"
14
14
  },
15
15
  "bin": {
16
- "cli-ns": "./bin/app.js"
16
+ "cli-ns": "./app.js"
17
17
  },
18
- "keywords": [],
18
+ "keywords": [
19
+ "static-server",
20
+ "cli",
21
+ "http-server",
22
+ "web-server"
23
+ ],
19
24
  "author": "",
20
25
  "license": "ISC",
21
26
  "dependencies": {
22
- "dotenv": "^17.2.3",
23
27
  "http-proxy": "^1.18.1"
24
28
  }
25
29
  }
package/.env DELETED
@@ -1,3 +0,0 @@
1
- STATIC_PATH=./dist
2
- PORT=8997
3
- PROXYS=[{"path":"/jshERP-boot","target":"http://10.0.8.221:9997"}]
package/bin/app.js DELETED
@@ -1,11 +0,0 @@
1
- #!/usr/bin/env node
2
- function run(argv) {
3
- if (argv[0] === "-v" || argv[0] === "--version") {
4
- console.log(" version is 0.0.1");
5
- } else if (argv[0] === "-h" || argv[0] === "--help") {
6
- console.log(" usage:\n");
7
- console.log(" -v --version [show version]");
8
- }
9
- return "version is 1.0.1";
10
- }
11
- run(process.argv.slice(2));