Skip to content

Commit

Permalink
Cli open file
Browse files Browse the repository at this point in the history
  • Loading branch information
platypii committed Jun 6, 2024
1 parent a854f08 commit 36c4467
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 11 deletions.
3 changes: 2 additions & 1 deletion src/cli.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,6 @@
if (process.argv[2] === 'chat') {
import('./chat.js').then(({ chat }) => chat())
} else {
import('./serve.js').then(({ serve }) => serve())
// Load file or directory
import('./serve.js').then(({ serve }) => serve({ path: process.argv[2] }))
}
25 changes: 15 additions & 10 deletions src/serve.js
Original file line number Diff line number Diff line change
Expand Up @@ -122,11 +122,10 @@ async function handleStatic(filePath, range) {

/**
* Serve head request
* @param {string} pathname
* @param {string} filePath
* @returns {Promise<ServeResult>}
*/
async function handleHead(pathname) {
const filePath = path.join(process.cwd(), pathname)
async function handleHead(filePath) {
const stats = await fs.stat(filePath).catch(() => undefined)
if (!stats || !stats.isFile()) {
console.error(`file not found ${filePath}`)
Expand All @@ -149,18 +148,23 @@ async function handleHead(pathname) {
* @returns {Promise<ServeResult>}
*/
async function handleListing(prefix) {
const dir = `${process.cwd()}/${prefix}`
console.log(`listing files with prefix '${prefix}'`)
if (!prefix) {
prefix = process.cwd()
} else if (!prefix.startsWith('/')) {
prefix = `${process.cwd()}/${prefix}`
}
try {
const stat = await fs.stat(dir)
const stat = await fs.stat(prefix)
if (!stat.isDirectory()) return { status: 400, content: 'not a directory' }
} catch (error) {
return { status: 404, content: 'not found' }
}

const files = []
for (const filename of await fs.readdir(dir, { recursive: false })) {
for (const filename of await fs.readdir(prefix, { recursive: false })) {
// get stats for each file
const filePath = `${dir}/${filename}`
const filePath = `${prefix}/${filename}`
const stat = await fs.stat(filePath)

if (stat.isFile()) {
Expand All @@ -182,9 +186,9 @@ async function handleListing(prefix) {

/**
* Start http server on given port
* @param {number} port
* @param {{ port?: number, path?: string }} options
*/
export function serve(port = 2048) {
export function serve({ port = 2048, path = '' }) {
// create http server
http.createServer(async (req, res) => {
const startTime = new Date()
Expand Down Expand Up @@ -240,7 +244,8 @@ export function serve(port = 2048) {
}
}).listen(port, () => {
console.log(`hyperparam server running on http://localhost:${port}`)
openUrl(`http://localhost:${port}`)
if (path) openUrl(`http://localhost:${port}/files/${path}`)
else openUrl(`http://localhost:${port}`)
})
}

Expand Down

0 comments on commit 36c4467

Please sign in to comment.