Node.js
Attach chrome debugger
https://frontendmasters.com/blog/node-js-debugging-in-chrome-devtools/
- open debugger at chrome://inspect/#devices
- run
node --inspect-brk app.jsin terminal - profit
Misc meanings
process.cwd() - shows current local working directory, example output - /home/user/repos/node-project
Express
npm install checklist
- express
- express-validator
- pg
- pg-format
- dotenv
- ejs
__dirname
__dirname is only for commonJS
if type is module (i.e. using ES Module) in package.json, add this to the top of app.js
import path from "path";
import { fileURLToPath } from "url";
const __dirname = path.dirname(fileURLToPath(import.meta.url));
multer
req.file object if using diskStorage
{
fieldname: 'uploaded_file',
originalname: 'p04-icon-teru_teru_bozu.gif',
encoding: '7bit',
mimetype: 'image/gif',
destination: './public/uploads/',
filename: '9b6d8cb5d83c270624d13b8c8d1d11f2',
path: 'public/uploads/9b6d8cb5d83c270624d13b8c8d1d11f2',
size: 171
}
Downloading a blob (from supabase)
this is the only way to download files from a private bucket
//"data" is a blob
const { data } = await supabase.download(supabasePath);
//transform blob into DataView
const download = new DataView(await data.arrayBuffer());
//creates file in system
await fs.appendFile(
process.cwd() + `/public/uploads/${file.name}`,
download
);
//delete file in system after 30 seconds
setTimeout(async () => {
await fs.unlink(process.cwd() + `/public/uploads/${file.name}`);
console.log("delete!")
}, 30000);
res.download(process.cwd() + `/public/uploads/${file.name}`);
fs
create directory
await fs.mkdir(process.cwd() + `/public/uploads/${username}`);
remove directory
await fs.rmdir(
process.cwd() +
`/public/uploads/${req.user.username}/${targetFoldername}`,
{ recursive: true },
(err) => {
throw new Error(err);
}
);
rename directory
await fs.rename(
process.cwd() + `/public/uploads/${req.user.username}/${targetFoldername}`,
process.cwd() + `/public/uploads/${req.user.username}/${foldername}`
);
best practice stuff
https://expressjs.com/en/advanced/best-practice-performance.html#set-node_env-to-production
try-catch blocks
try-catch only works with synchronous stuff, so no need
best to handle errors in the controller, rather than rely on the error handler in app.js
NODE_ENV
Setting NODE_ENV to “production” makes Express:
Cache view templates.
Cache CSS files generated from CSS extensions.
Generate less verbose error messages.