Last active
February 8, 2024 21:43
-
-
Save paruljain/0e06ca76081017e0358fd425a4cf8008 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const http = require('http'); | |
const fs = require('fs'); | |
const path = require('path'); | |
const server = http.createServer((req, res) => { | |
const url = decodeURI(req.url); | |
const filePath = path.join(__dirname, url); | |
if (req.method === 'PROPFIND') { | |
fs.readdir(filePath, (err, files) => { | |
if (err) { | |
res.writeHead(500); | |
return res.end(err.message); | |
} | |
const responseXml = generatePropfindXml(files); | |
res.writeHead(200, { 'Content-Type': 'text/xml' }); | |
res.end(responseXml); | |
}); | |
} else if (req.method === 'GET') { | |
fs.readFile(filePath, (err, data) => { | |
if (err) { | |
res.writeHead(404); | |
return res.end('File not found'); | |
} | |
res.writeHead(200); | |
res.end(data); | |
}); | |
} else { | |
res.writeHead(405, { 'Allow': 'PROPFIND, GET' }); | |
res.end('Method Not Allowed'); | |
} | |
}); | |
function generatePropfindXml(files) { | |
let xml = '<?xml version="1.0" encoding="utf-8"?>\n'; | |
xml += '<D:multistatus xmlns:D="DAV:">\n'; | |
files.forEach(file => { | |
const stats = fs.statSync(file); | |
const isDirectory = stats.isDirectory(); | |
xml += ' <D:response>\n'; | |
xml += ` <D:href>/${file}</D:href>\n`; | |
xml += ` <D:propstat>\n`; | |
xml += ` <D:prop>\n`; | |
xml += ` <D:resourcetype>${isDirectory ? '<D:collection/>' : ''}</D:resourcetype>\n`; | |
xml += ` </D:prop>\n`; | |
xml += ` <D:status>HTTP/1.1 200 OK</D:status>\n`; | |
xml += ` </D:propstat>\n`; | |
xml += ` </D:response>\n`; | |
}); | |
xml += '</D:multistatus>\n'; | |
return xml; | |
} | |
const PORT = process.env.PORT || 3000; | |
server.listen(PORT, () => { | |
console.log(`Server is running on port ${PORT}`); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment