Created
April 11, 2019 14:09
-
-
Save antstanley/771999f3ed9aaa2e48588cfa03a0cbb2 to your computer and use it in GitHub Desktop.
Google Run test code with file system layout
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 express = require('express') | |
const fs = require('fs') | |
const path = require('path') | |
const app = express() | |
let coldstart = true | |
const fsExplore = async dir => { | |
try { | |
const dirContents = fs.readdirSync(dir, { | |
encoding: 'utf8', | |
withFileTypes: true | |
}) | |
let dirObject = {} | |
for (let i = 0; i < dirContents.length; i++) { | |
const filename = dirContents[i].name | |
if (dirContents[i].isDirectory()) { | |
const fullDir = path.join(dir, filename) | |
dirObject[filename] = await fsExplore(fullDir) | |
} else { | |
try { | |
const fileStats = fs.statSync(path.join(dir, filename)) | |
const unixFilePermissions = | |
'0' + (fileStats.mode & parseInt('777', 8)).toString(8) | |
dirObject[filename] = { | |
unixFilePermissions, | |
size: fileStats.size | |
} | |
} catch (error) { | |
dirObject[filename] = error | |
} | |
} | |
} | |
return dirObject | |
} catch (error) { | |
console.log(error) | |
return error | |
} | |
} | |
const dirExplore = async dir => { | |
try { | |
const dirContents = fs.readdirSync(dir, { | |
encoding: 'utf8', | |
withFileTypes: true | |
}) | |
let dirObject = {} | |
let dirSize = 0 | |
for (let i = 0; i < dirContents.length; i++) { | |
const filename = dirContents[i].name | |
if (dirContents[i].isDirectory()) { | |
const fullDir = path.join(dir, filename) | |
dirObject[filename] = await dirExplore(fullDir) | |
dirSize += dirObject[filename]._size | |
} else { | |
try { | |
const fileStats = fs.statSync(path.join(dir, filename)) | |
dirSize += fileStats.size | |
} catch (error) { | |
dirSize += 0 | |
} | |
} | |
} | |
dirObject['_size'] = dirSize | |
return dirObject | |
} catch (error) { | |
console.log(error) | |
return error | |
} | |
} | |
app.get('/', async (req, res) => { | |
if (coldstart) { | |
console.log('First request after coldstart') | |
coldstart = false | |
} | |
const rootDir = path.join(__dirname, '..', '..', '..') | |
if (req.query.inspect == 'file') { | |
const fileData = await fsExplore(rootDir) | |
res.send(JSON.stringify(fileData, null, 2)) | |
} else { | |
if (req.query.inspect == 'directory') { | |
const dirData = await dirExplore(rootDir) | |
res.send(JSON.stringify(dirData, null, 2)) | |
} else { | |
const target = process.env.TARGET || 'World' | |
res.send(`Hello ${target}!`) | |
} | |
} | |
}) | |
const port = process.env.PORT || 8080 | |
app.listen(port, () => { | |
console.log('Coldstart!', port) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment