如何将Node.js单文件无依赖的静态服务器改写为支持长尾词查询的?

2026-04-06 12:241阅读0评论SEO教程
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计837个文字,预计阅读时间需要4分钟。

如何将Node.js单文件无依赖的静态服务器改写为支持长尾词查询的?

web.js**简单的静态服务器,单文件无依赖**javascriptvar http=require('http');var fs=require('fs');var url=require('url');var path=require('path');const { exec }=require('child_process');

如何将Node.js单文件无依赖的静态服务器改写为支持长尾词查询的?

const VERSION=[0, ''];

http.createServer((req, res)=> { var parsedUrl=url.parse(req.url, true); var filePath=path.join(__dirname, parsedUrl.pathname);

fs.readFile(filePath, (err, data)=> { if (err) { res.writeHead(404, { 'Content-Type': 'text/plain' }); res.end('404 Not Found\n'); } else { res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end(data); } });}).listen(8080);

console.log('Server running on port 8080');

web.js

/** * 简单的静态服务器,单文件无依赖 * @author xBei */ var " + request.headers.host + pathName; response.writeHead(301, { location: redirect }); //response.end方法用来回应完成后关闭本次对话,也可以写入HTTP回应的具体内容。 response.end(); return; }; //处理默认文档 if (!defaultDocuments.every((value) => { var defaultFile = path.join(filePath, value); if (isFile(defaultFile)) { outputFile(request, response, defaultFile); return false; } return true; })) { return false; } //没有找到默认文档 //显示当前目录下所有文件 var html = ` ${pathName}`; html += `

${pathName}

    `; html += `
  • ..
  • `; //读取该路径下文件 fs.readdir(filePath, (err, files) => { if (err) { console.log("读取路径失败!", filePath); } else { for (var file of files) { html += `
  • ${file}
  • `; } } html += '
'; html += `
${new Date()}
`; html += '' response.writeHead(200, { "content-type": "text/html" }); response.end(html); }); } else { log(request, response, 500); response.writeHead(500, { "content-type": contentType }); response.end("

500 Server Error

"); } }; const defaultOptions = { port: 8080, help: false, version: false, update: false, }; function handlerArgs() { let args = process.argv; let argsCount = args.length; if (argsCount < 3) return Object.assign({}, defaultOptions, {}); args = args.slice(2); let options = {}; while (args.filter((v) => { return v.startsWith('-') }).length > 0) { let count = args.length; args.every((v, index) => { if (v.startsWith('-')) { if (index + 1 < count) { let vv = args[index + 1]; if (!vv.startsWith('-')) { options[v] = vv; args.splice(index, 2); } else { options[v] = true; args.splice(index, 1); } } else { options[v] = true; args.splice(index, 1); } return false; } return true; }); } for (let key in options) { let element = options[key]; switch (key) { case '-p': case '--port': options['port'] = element; break; case '-H': case '--help': options['help'] = element; break; default: options[key.replace(/^-{1,}/, '')] = element; break; } delete options[key]; } //console.log(options); return Object.assign({}, defaultOptions, options); } function showHelp() { let me = __filename.split(path.sep).pop(); console.log(`把当前目录(${me}所在目录)当作“主目录”创建一个简单的静态服务器`); console.log(`用法:node ${me} [选项]`); console.log(); console.log('版本:', VERSION.join('.')); console.log('选项:'); console.log(' -P, --port

', "\t 监听的端口号(大于1024)。默认:8080"); console.log(' -U, --update', "\t\t 在线更新"); console.log(' -V, --version', "\t\t 显示版本"); console.log(' -H, --help', "\t\t 显示帮助"); } let options = handlerArgs(); if (options.help === true) { //console.log(process.argv) showHelp(); process.exit(0); } else if (options.version == true) { console.log('版本:', VERSION.join('.')); }else if (options.update === true) { doUpdate(); } else { let port = options.port; if (!port || isNaN(port + '')) { showHelp(); process.exit(1); } else { if (port < 1024 || port > 65535) { console.error("port must be > 1024 AND < 65535"); process.exit(1); } } var localhost:${port}/'`); break; case 'freebsd': case 'linux': case 'sunos': exec(`x-www-browser 'localhost:${port}/'`); break; case 'win32': exec(`start localhost:${port}/`); break; default: break; } }); } function setColor(color, text) { let a = styles[color]; if (!a) return text; return `${a[0]}${text}${a[1]}`; } //console.log('\x1B[36m%s\x1B[0m2222', 123); //cyan //console.log('\x1B[33m%s\x1b[0m:', path); //yellow //gitee.com/xbei/codes/cy07qm6idzvst52lp38eh46/raw?blob_name=web.js function downFile(urlToDownload, toSave) { return new Promise((resolve, reject) => { var gitee.com/xbei/codes/cy07qm6idzvst52lp38eh46/raw?blob_name=web.js', tmpFile) .then((content) => { //判断是否可更新 //let match = /^ \* @version (\d+).(\d+).(\d+)/ig.exec(content); //const VERSION = [0, 1, 1]; let match = /const VERSION = \[(\d+), (\d+), (\d+)\];/ig.exec(content); if (match) { if (VERSION[0] < match[1] || VERSION[1] < match[2] || VERSION[2] < match[3]) { console.log(`最新版本: ${match[1]}.${match[2]}.${match[3]}`); return true; } } return false; }) .then(canUpdate => { if (canUpdate) { fs.copyFile(tmpFile, selfFile, (err) => { if (err) throw err; console.log(setColor('green','更新成功')); fs.unlink(tmpFile, err => { }); }); } else { console.log('已经是最新版了,不需要更新'); } }) .catch(e => { console.error(`[${setColor('red', '错误')}]: ${e.message}`); }); }

本文共计837个文字,预计阅读时间需要4分钟。

如何将Node.js单文件无依赖的静态服务器改写为支持长尾词查询的?

web.js**简单的静态服务器,单文件无依赖**javascriptvar http=require('http');var fs=require('fs');var url=require('url');var path=require('path');const { exec }=require('child_process');

如何将Node.js单文件无依赖的静态服务器改写为支持长尾词查询的?

const VERSION=[0, ''];

http.createServer((req, res)=> { var parsedUrl=url.parse(req.url, true); var filePath=path.join(__dirname, parsedUrl.pathname);

fs.readFile(filePath, (err, data)=> { if (err) { res.writeHead(404, { 'Content-Type': 'text/plain' }); res.end('404 Not Found\n'); } else { res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end(data); } });}).listen(8080);

console.log('Server running on port 8080');

web.js

/** * 简单的静态服务器,单文件无依赖 * @author xBei */ var " + request.headers.host + pathName; response.writeHead(301, { location: redirect }); //response.end方法用来回应完成后关闭本次对话,也可以写入HTTP回应的具体内容。 response.end(); return; }; //处理默认文档 if (!defaultDocuments.every((value) => { var defaultFile = path.join(filePath, value); if (isFile(defaultFile)) { outputFile(request, response, defaultFile); return false; } return true; })) { return false; } //没有找到默认文档 //显示当前目录下所有文件 var html = ` ${pathName}`; html += `

${pathName}

    `; html += `
  • ..
  • `; //读取该路径下文件 fs.readdir(filePath, (err, files) => { if (err) { console.log("读取路径失败!", filePath); } else { for (var file of files) { html += `
  • ${file}
  • `; } } html += '
'; html += `
${new Date()}
`; html += '' response.writeHead(200, { "content-type": "text/html" }); response.end(html); }); } else { log(request, response, 500); response.writeHead(500, { "content-type": contentType }); response.end("

500 Server Error

"); } }; const defaultOptions = { port: 8080, help: false, version: false, update: false, }; function handlerArgs() { let args = process.argv; let argsCount = args.length; if (argsCount < 3) return Object.assign({}, defaultOptions, {}); args = args.slice(2); let options = {}; while (args.filter((v) => { return v.startsWith('-') }).length > 0) { let count = args.length; args.every((v, index) => { if (v.startsWith('-')) { if (index + 1 < count) { let vv = args[index + 1]; if (!vv.startsWith('-')) { options[v] = vv; args.splice(index, 2); } else { options[v] = true; args.splice(index, 1); } } else { options[v] = true; args.splice(index, 1); } return false; } return true; }); } for (let key in options) { let element = options[key]; switch (key) { case '-p': case '--port': options['port'] = element; break; case '-H': case '--help': options['help'] = element; break; default: options[key.replace(/^-{1,}/, '')] = element; break; } delete options[key]; } //console.log(options); return Object.assign({}, defaultOptions, options); } function showHelp() { let me = __filename.split(path.sep).pop(); console.log(`把当前目录(${me}所在目录)当作“主目录”创建一个简单的静态服务器`); console.log(`用法:node ${me} [选项]`); console.log(); console.log('版本:', VERSION.join('.')); console.log('选项:'); console.log(' -P, --port

', "\t 监听的端口号(大于1024)。默认:8080"); console.log(' -U, --update', "\t\t 在线更新"); console.log(' -V, --version', "\t\t 显示版本"); console.log(' -H, --help', "\t\t 显示帮助"); } let options = handlerArgs(); if (options.help === true) { //console.log(process.argv) showHelp(); process.exit(0); } else if (options.version == true) { console.log('版本:', VERSION.join('.')); }else if (options.update === true) { doUpdate(); } else { let port = options.port; if (!port || isNaN(port + '')) { showHelp(); process.exit(1); } else { if (port < 1024 || port > 65535) { console.error("port must be > 1024 AND < 65535"); process.exit(1); } } var localhost:${port}/'`); break; case 'freebsd': case 'linux': case 'sunos': exec(`x-www-browser 'localhost:${port}/'`); break; case 'win32': exec(`start localhost:${port}/`); break; default: break; } }); } function setColor(color, text) { let a = styles[color]; if (!a) return text; return `${a[0]}${text}${a[1]}`; } //console.log('\x1B[36m%s\x1B[0m2222', 123); //cyan //console.log('\x1B[33m%s\x1b[0m:', path); //yellow //gitee.com/xbei/codes/cy07qm6idzvst52lp38eh46/raw?blob_name=web.js function downFile(urlToDownload, toSave) { return new Promise((resolve, reject) => { var gitee.com/xbei/codes/cy07qm6idzvst52lp38eh46/raw?blob_name=web.js', tmpFile) .then((content) => { //判断是否可更新 //let match = /^ \* @version (\d+).(\d+).(\d+)/ig.exec(content); //const VERSION = [0, 1, 1]; let match = /const VERSION = \[(\d+), (\d+), (\d+)\];/ig.exec(content); if (match) { if (VERSION[0] < match[1] || VERSION[1] < match[2] || VERSION[2] < match[3]) { console.log(`最新版本: ${match[1]}.${match[2]}.${match[3]}`); return true; } } return false; }) .then(canUpdate => { if (canUpdate) { fs.copyFile(tmpFile, selfFile, (err) => { if (err) throw err; console.log(setColor('green','更新成功')); fs.unlink(tmpFile, err => { }); }); } else { console.log('已经是最新版了,不需要更新'); } }) .catch(e => { console.error(`[${setColor('red', '错误')}]: ${e.message}`); }); }