-
Notifications
You must be signed in to change notification settings - Fork 240
Node form data solution #151
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: master
Are you sure you want to change the base?
Changes from 1 commit
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,8 +1,54 @@ | ||
| 'use strict'; | ||
|
|
||
| const http = require('http'); | ||
| const fs = require('fs'); | ||
| const path = require('path'); | ||
|
|
||
| function createServer() { | ||
| /* Write your code here */ | ||
| // Return instance of http.Server class | ||
| const server = new http.Server(); | ||
|
|
||
| server.on('request', (req, res) => { | ||
| const url = new URL(req.url, `http://${req.headers.host}`); | ||
|
|
||
| if (url.pathname === '/' && req.method === 'GET') { | ||
| fs.createReadStream(path.resolve('public', 'index.html')).pipe(res); | ||
|
|
||
| return; | ||
| } | ||
|
|
||
| if (url.pathname === '/add-expense' && req.method === 'POST') { | ||
| const chunks = []; | ||
|
|
||
| req.on('data', (chunk) => { | ||
| chunks.push(chunk); | ||
| }); | ||
|
|
||
| req.on('end', () => { | ||
| const expensePath = path.resolve(__dirname, '..', 'db/expense.json'); | ||
| const data = Buffer.concat(chunks).toString(); | ||
|
|
||
| if (Object.keys(JSON.parse(data)).length !== 3) { | ||
| res.statusCode = 400; | ||
| res.setHeader('Content-type', 'text/plain'); | ||
| res.end('All params must be completed'); | ||
|
|
||
| return; | ||
| } | ||
|
|
||
| fs.writeFileSync(expensePath, data); | ||
| res.statusCode = 200; | ||
| res.setHeader('Content-type', 'application/json'); | ||
| res.end(data); | ||
| }); | ||
|
Comment on lines
+62
to
+66
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. You are using |
||
|
|
||
| return; | ||
| } | ||
|
|
||
| res.statusCode = 404; | ||
| res.end('Page not found'); | ||
| }); | ||
|
|
||
| return server; | ||
| } | ||
|
|
||
| module.exports = { | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Issue: Using
fs.writeFileSyncinside an asynchronous request handler can block the event loop and degrade server performance, especially under concurrent requests. Consider usingfs.writeFile(the asynchronous version) with a callback to avoid blocking the server.