Friday, 27 January 2017

How to manage Log and rotate-file in Nodejs

Why log and log rotate?
Log is a file that records either events that occur in an application or messages between different users of a communication.

Benefits

  • For better debugging and find the problems.
  • For better application management. 
  • For security reason to tracking an application behaviors. 

How we can achieve these above points in Nodesjs 
Step 1-  Require a npm modules - winston and winston-daily-rotate-file
  • npm i winsto
  • npm i winston-daily-rotate-file

Step 2-  Create a logger configuration JavaScript (.js) file and add below code inside created file. I have created logger.js file.
logger.js : 

var winston = require('winston');
require('winston-daily-rotate-file');
  
  var transport = new winston.transports.DailyRotateFile({
    filename: './log',                            // Log file name  and location 
    datePattern: 'yyyy-MM-ddTHH.',  // Log rotate duration is hourly basis
    prepend: true,
    level: process.env.ENV == 'development' ? 'info' : 'debug'  //As per requirement - local server or production 
  });
  
  var logger = new (winston.Logger)({
    transports: [
      transport
    ]
  });
module.exports = logger;  //Export it as module

Step 3- We have created a module called logger. Now we need to include it on our app.js or server.js (Enter point of Node server where we include all other dependency)
i.e - app.js (I have created a app.js file as entry file in node run environment)

global.logger = require('logger'); //Include a Export Module 
logger.info('Hello World!');         // set logger for information - same as console.log() function 
logger.debug('Hello World!');     // set logger for debug purpose  - log and debug as per your requirement  
Step 4- Run your application - node app.js

It creates file on hourly basis. In our case it created file 2017-01-27T11.log file in parallel of app.js file.
content of 2017-01-27T11.log file is : 
{"level":"info","message":"Hello World!","timestamp":"2017-01-27T11:43:22.529Z"}
{"level":"debug","message":"Hello World!","timestamp":"2017-01-27T11:43:22.570Z"}
- It will create new log file as hourly basis.
i.e  2017-01-27T11.log 
     2017-01-27T12.log

You can drop comment for any questions or feedback.Will get back to you soon.

Wednesday, 20 April 2016

How to authenticate mongodb

About MongoDB, cross-platform document-oriented database. Classified as a NoSQL database, MongoDB eschews the traditional table-basedrelational database structure in favor of JSON-like documents with dynamic schemas (MongoDB calls the format BSON), making the integration of data in certain types of applications easier and faster.


Here I am going to explain how to apply user-name and password(authenticate) to mongoDB's database.


#1. Open shell command. Fire this command
command - mongo
output-
MongoDB shell version: 3.0.4
connecting to: test

#2. 
command - show dbs;
output- 
admin       0.078GB
local         0.078GB
auth_db    0.078GB

#3. 
command - use auth_db;
output- 
switched to auth_db

Here, we have selected auth_db Database for apply authentication.
#4. Fire query : 

db.createUser({user:"YOUR_USERNAME", pwd:"YOUR_PWD",roles:["readWrite","dbAdmin"]})

We have created User of database 'auth_db' 
You can set your user-name and password to above query.

#5. Make sure authentication is true. You can set authentication = true in mongod.conf file. 

Option 1: In mongod.conf, Remove comment and make it true.
auth=true; 

- restart mongoDB - sudo service mongod restart

Option 2 : command to run mongodb with auth true :- mongod -auth

#6. In database config file in Nodejs 

var mongoose = require('mongoose');
var uri = 'mongodb://localhost:27017/auth_db';
var options = {
 user: 'YOUR_USERNAME',
 pass: 'YOUR_PWD'
}
mongoose.connect(uri, options, function(err, result){
   console.log('err -->' + JSON.stringify(err));
});

Without user-name and password, would not able to perform operation with database.

If you don't want to use authentication to database just make auth=true is commented in mongod.conf file or start mongo without -auth i.e mongo

do not forgot restart mongodb.
--

You can drop comment for any questions or feedback. Will get back to you soon.



Tuesday, 20 October 2015

How to get Video Details including orientation duration Using FFMPEG

Here I am going to get details related to FFMPEG including orientation, duration.

Step to get details related to FFMPEG including orientation, duration.

#1. Get Video duration:


$ffmpeg_path = "/usr/bin/ffmpeg"; //Path to your FFMPEG
$video_path = "/vidoes/myvideo.mov"; // Path to your Video


$command = $ffmpeg_path . ' -i "' . $video_path . '" -vstats 2>&1';

$output = shell_exec($command);
$regex_duration = "/Duration: ([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}).([0-9]{1,2})/";
if (preg_match($regex_duration, $output, $regs)) {
$hours = $regs [1] ? $regs [1] : null;
$mins = $regs [2] ? $regs [2] : null;
$secs = $regs [3] ? $regs [3] : null;
}
$video_Length = $hours . ":" . $mins . ":" . $secs;


#2. Get Video thumbnail:

$save_video_thumbnail = 'thumbnails/myvideo_thumbnail';


$cmd = "$ffmpeg_path -i $video_path -ss 00:00:03 -s 404x694 -vframes 1 $save_video_thumbnail";

$output = shell_exec($command);

Notes : In Above 00:00:03 is duration when thumbnail is generated. We can set this as per requirement.

#3. Get Video Orientation:

$ffmpeg_path = "/usr/bin/ffmpeg"; //Path to your FFMPEG
$video_path = "/vidoes/myvideo.mov"; // Path to your Video


$command = $ffmpeg_path . ' -i "' . $video_path . '" -vstats 2>&1';
$output = shell_exec($command);

$out_arr = explode("\n", $output);
foreach($out_arr as $line) {
if( preg_match('/^Stream.*Video:/', trim($line)) ) {
/* match line: Stream #0.0(und): Video: h264 (High), yuv420p, 640x360 [PAR 1:1 DAR 16:9], 597 kb/s, 25 fps, 25 tbr, 25k tbn, 50 tbc */
$line_arr = explode(',', $line);
// get field: 640x360 [PAR 1:1 DAR 16:9]
$target_arr = explode(' ', $line_arr[3]);
// get parts: 640x360
$dims = explode('x', $target_arr[1]);
$res_x = $dims[0];
$res_y = $dims[1];
}
}

$orientation = (intval($res_x) > intval($res_y)) ? 'Portrait' : 'Landscape';


You can drop comment for any questions or feedback. Will get back to you soon.

For more such technical blogs, visit us http://www.solutionanalysts.com/blog







Friday, 19 December 2014

Fancytree -Drag'n'drop and Save order



Here I am going to integrate fancytree and functionality that save the order according drag'n'drop in fancytree.

Steps for how to create fancytree and save order according drag'n'drop.

Steps :


1. Download Fancytree plugin from the below url
                 http://plugins.jquery.com/fancytree

2. Extract that downloaded folder and put it in your xampp->htdocs-> or virtual host folder(I have put in my virtual host folder name examples).


3. Rename this folder like fancytree and open it.


4. We don’t need all contents from it. we need only following files.


a. fancytree \src\skin-xp

b. src/jquery.fancytree.js
c. src/jquery.fancytree.dnd.js
d. src/jquery.fancytree.edit.js
e. src/skin-xp/ui.fancytree.css

5. Apart from that, we need two jquery files.


a. jquery.js         http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.js


b. jquery-ui.js    http://ajax.googleapis.com/ajax/libs/jqueryui/1/jquery-ui.js


6. Now create one php file. I have created createtree.php


 Insert following content in head section of this page.


7. Put this below code in javascript section.


8. Now create one <div> in body section of page.


9. You can add your code in this above div as per requirement. I have added this code which came from database. 

Data coming from three different table. 
 1. topcategory

2. subcategory 
- id field from topcategory table reference as foreign key in subcategory table filed topcategory_id

3. questions 
- id filed from subcategory table reference as foreign key in question table filed subcategory_id 

Here data display through three array $questionaire, $category, $question.

10. Now open your browser and open the php/html file.


  - for me it is: http://examples/fancytree/createtree.php


11. You can see the fancytree structure with your data.


If you have any requirement to save order using drag'n'drop then follow the simple steps.


1. We need one field name like order_number in table from where data come. order_number store order of data. I have added order_number in questions table.

2. We have to fetch data from table by order(In order of order_number).

3. Now add following code in dragStop event of fancytree in Javascript.

4. You can see in above code, there is a array named as "neworder" that contains new order numbers of our data.



5. Here we can call one ajax with data using "neworder" array which actually has new order and we can update data's order number in table.


Notes : For this example, we have changed the order at the third level data and store those data's order in table.

You can add/use extra options from here as well. GIT-URL

Contributors

1. Bhavin Patel
2Nrupen Desai

You can drop comment for any questions or feedback. We will get back to you soon.

For more such technical blogs, visit us http://www.solutionanalysts.com/blog