About Me
- I was Frontend Team Manager at Pyramid Consulting
- I am a technical lead at NAU Studio
- I was Flash Developer, Frontend Developer
- I am Fullstack Developer
Contents
- Take advantage of latest feature of language (ES6)
- Setup correct development environment
- Establish coding style in development team
- Secure Application Server
- Debug NodeJS application
- Profiling NodeJS application
- Monitor NodeJS application
Latest feature of javascript
- let, const
- object literal
- template literal
- arrow function
- destructuring
- iterator
- generator
- promise
Sample Code
const crypto = require('crypto');
const fs = require('fs');
class Utils {
decodeBase64(base64str, file) {
const p = new Promise((resolve, reject) => {
// create buffer object from base64 encoded string, it is important to tell the constructor that the string is base64 encoded
var binary = new Buffer(base64str, 'base64');
// write buffer to file
fs.writeFile(file, binary, (err, result) => {
if (err) {
reject(err);
} else {
resolve(result);
}
});
});
return p;
}
}
module.exports = new Utils();
Sample Code
UserModel.observe('before save', function (context, next) {
let data = context.instance ? context.instance : context.data;
const hasBase64InAvatar = (data.avatar || '').indexOf('base64,') > -1;
let [fileType, base64] = [];
if (hasBase64InAvatar) {
[fileType, base64] = data.avatar.split('base64,');
data.base64 = base64;
[, fileType] = fileType.split('/');
}
let fileName = data.username || (context.currentInstance ? context.currentInstance.username : new Date());
if (fileType) {
fileType = fileType.replace(';', '');
fileName += fileType ? '.' + fileType : '';
}
// We need to add roles to user if uploading data has roles
let allPromises = [];
if (_.isObjectLike(data.roles)) {
const roles = _.isArray(data.roles) ? data.roles : [data.roles];
allPromises.push(UserModel._addRoles({roles, userId}));
delete data.roles;
}
if ((data.base64 || '').length > 100) {
allPromises.push(
new Promise((resolve, reject) => {
UserModel
._saveImage(data.base64, fileName)
.then((result) => {
data.avatar = result;
resolve(true);
})
.catch((err) => {
reject(err);
});
})
);
delete data.base64;
}
Promise.all([...allPromises]).then((values) => {
console.log('resolve all ', values);
next();
});
});
Setup Development Environment
- Use latest LST version of NodeJS
- Manage NodeJS dependencies
- Using npm to create build script
- Code linter
- Unit Test
Establish Coding Style
- Coding convention
- All dependencies should be required at top of file
- Import only what we need
- Standardize the way of controlling async flow
nodejs-in-practice
By Quy Tran
nodejs-in-practice
- 1,144