Last active
October 5, 2023 12:39
-
-
Save sankar4n/94331a1d610a2f8428097cb394457e45 to your computer and use it in GitHub Desktop.
req-logger
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
{ | |
"name": "req-dump", | |
"version": "1.0.0", | |
"description": "", | |
"main": "server.js", | |
"bin": "server.js", | |
"scripts": { | |
"test": "echo \"Error: no test specified\" && exit 1", | |
"start": "node server.js" | |
}, | |
"author": "Sankaran Kaliappan <[email protected]>", | |
"license": "ISC", | |
"dependencies": { | |
"body-parser": "^1.19.0", | |
"express": "^4.17.1" | |
} | |
} |
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
#!/usr/bin/env node | |
const express = require('express') | |
const bodyParser = require('body-parser') | |
const fs = require('fs') | |
const app = express() | |
const port = process.env.PORT || 3000 | |
function array2csv(data) { | |
const replacer = (key, value) => value === null ? '' : value // specify how you want to handle null values here | |
const header = Object.keys(data[0]) | |
const csv = [ | |
header.join(','), // header row first | |
...data.map(row => header.map(fieldName => JSON.stringify(row[fieldName], replacer)).join(',')) | |
].join('\r\n') | |
return csv; | |
} | |
// send formated json response | |
app.set('json spaces', 2) | |
// parse application/x-www-form-urlencoded | |
app.use(bodyParser.urlencoded({ extended: true })) | |
// parse application/json | |
app.use(bodyParser.json({ limit: '10mb' })) | |
// parse an HTML body into a string | |
app.use(bodyParser.text({ type: 'text/html' })) | |
app.post('/json2csv', (req, res) => { | |
const outputFilename = `./${req.body.file_name || 'output'}.csv`; | |
fs.writeFileSync(outputFilename, array2csv(req.body.payload)); // write to the file system | |
res.json({output: outputFilename}); | |
}); | |
app.all('*', (req, res) => { | |
const { headers, method, url, body, query } = req | |
console.log({ headers, method, url, body, query }) | |
res.send({ | |
headers, method, url, body, query, | |
}) | |
}) | |
app.listen(port, () => console.log(`listening at http://localhost:${port}`)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment