Khov Ea Hang
learn hard and play hard make the life happy. Enjoy!
Friday, April 12, 2019
Monday, March 5, 2018
How to show all globally installed NPM packages
In this post, I want to show you how to list all installed NPM packages.
Type this command:
Type this command:
npm ls
npm list
npm la
npm ll
it will list all packages in current folder but it is locally not in globally. To do this we need to add option -g so it will list all with sub tree of packages.
On the other hand, if you can show only top level by add --depth=0
npm list -g
On the other hand, if you can show only top level by add --depth=0
npm list -g --depth=0
Wednesday, March 15, 2017
How to upload file( only image) with nodeJs
Objective: uploading only image which we filters such as 'png', 'jpg' or 'jpeg' file with customized file name. Here are source code github
We use expressjs framework with multer middleware for handling file upload
+ View file: add enctype="multipart/form-data"
+ Create function for filtering file extension.
+ Define upload directory to be store uploaded file.
+ use middleware to upload url
Source Code: download here
Reference: https://www.npmjs.com/package/multer
We use expressjs framework with multer middleware for handling file upload
Multer is a node.js middleware for handling multipart/form-data, which is primarily used for uploading files. It is written on top of busboy for maximum efficiency.Implementation
NOTE: Multer will not process any form which is not multipart (multipart/form-data).
+ View file: add enctype="multipart/form-data"
<form action="/" method="post" enctype="multipart/form-data">
<input type="file" name="imageFile">
<input type="submit">
</form>
+ Create function for filtering file extension.
function fileFilter(req, file, cb){
var extensions = ['png','jpg','jpeg'];
var bool = false;
var extensionFile = getExtension(file);
for(var i=0; i<extensions.length; i++){
if(extensionFile == extensions[i]){
cb(null, true);
bool = true;
}
}
if(!bool) cb(new Error("We support only 'png', 'jpg', jpeg."));
}
function getExtension(file){
return file.originalname.substr(file.originalname.lastIndexOf(".")+1, file.originalname.length);
}
Throw Error |
+ Define upload directory to be store uploaded file.
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, __dirname + '/uploads')
},
filename: function (req, file, cb) {
cb(null, file.fieldname + '-' + Date.now() + "." + getExtension(file));
}
});
var upload = multer({ storage: storage, fileFilter: fileFilter });
+ use middleware to upload url
app.use('/',upload.single('imageFile'), index);
Source Code: download here
Reference: https://www.npmjs.com/package/multer
Thursday, December 15, 2016
Generate project expressjs
Overview: Expressjs is one of the most popular web framework which is build on top of nodejs. It is a minimal framework for creating server side or restful APIs (application programming interfaces).
Objective: Create project expressjs using express-generator
Quick Start:
First of all, you need to install express-generator
npm install -g express-generator
After installed let create the app by using key word express:
express --view<engine> project-name
Note: view <engine> support (ejs|hbs|hjs|jade|pug|twig|vash) (defaults to jade)Install dependencies and running project by default app run at http://localhost:3000
npm install
npm start
Here are Command Line Options
-h, --help output usage information
--version output the version number
-e, --ejs add ejs engine support
--hbs add handlebars engine support
--pug add pug engine support
-H, --hogan add hogan.js engine support
-v, --view add view support (ejs|hbs|hjs|jade|pug|twig|vash)
(defaults to jade)
-c, --css add stylesheet support (less|stylus|compass|sass)
(defaults to plain css)
--git add .gitignore
-f, --force force on non-empty directory
Thursday, December 8, 2016
Easy Step: Auto Start NodeJs Server on Startup Windows
Overview: Generally, when we start server nodejs we use command node server.js or node bin/www for express framework. Restarting or start computer you need to run that command line again. In the article I will show you some tips to solve to issue.
Objective: When computer startup service node js is automatically started.
Objective: When computer startup service node js is automatically started.
- Forever: make process run continuously and automatically restart when it exits unexpectedly.
Implementation:
- Install forever in globally
npm install -g forever
- Create VbScript for executing project: I put it in root of project directory
Set WshShell = WScript.CreateObject("WScript.Shell") Return = WshShell.Run("cmd.exe /C forever start bin/www", 1, true)
- Startup folder
You can link VBscript file(shortcut) to startup folder
- Restart computer
Monday, August 22, 2016
Logging NodeJs with Winston
Objective: We create log file (Daily log file: info.log.2016-08-22) Source code github
- Show log in Console and in File
Implementation
- Create project using Express generator
Note: if you don't have express generator you can install via command lineexpress -e winstonjs-console-and-file
npm install express-generator -g
- Install Winston
npm install --save winston@0.8.3
- Open app.js write some code
var FileStreamRotator = require('file-stream-rotator'); var fs = require('fs'); var logDirectory = __dirname + '/logs' // ensure log directory exists fs.existsSync(logDirectory) || fs.mkdirSync(logDirectory); // create a rotating write stream var accessLogStream = FileStreamRotator.getStream({ filename: logDirectory + '/access-%DATE%.log', frequency: 'daily', verbose: false, date_format: 'YYYY-MM-DD' }); app.use(morgan('combined', {stream: accessLogStream}));
- Create folder logger then file index.js
var winston = require("winston"); if(process.env == 'production') { winston.level = 'info'; } else { winston.level = 'debug'; } winston.loggers.add('info', { console: { level: winston.level, colorize: true, label: 'category one' }, file: { level: winston.level, colorize: 'true', filename: __dirname + '/../logs/info/info.log', datePattern: '.yyyy-MM-dd', //maxsize: 20000, json: false }, DailyRotateFile: { level: winston.level, colorize: 'true', filename: __dirname + '/../logs/info/info.log', datePattern: '.yyyy-MM-dd', //maxsize: 20000, json: false } }); module.exports = winston.loggers.get('info');
- How to use: call file /logger/index.js
var logger = require("../logger"); logger.info("This is logger.");
- Result: It shows in Console and File
Download Source code github
Subscribe to:
Posts (Atom)