Monday, 20 March 2017

Node js Tutorial for beginners with examples - page 5

Node js Tutorial for beginners with examples - page 5

Question: How to check if path is file or directory?
var fs = require("fs");
console.log(fs.lstatSync('/file').isDirectory()); //true/false

Other useful commands
fs.lstatSync('/file').isFile();
stats.isDirectory().isBlockDevice();
stats.isDirectory().isCharacterDevice();
stats.isDirectory().isSymbolicLink() (only valid with fs.lstat());
stats.isDirectory().isFIFO();
stats.isDirectory().isSocket();



Question: How to create a new directory? If does not exist.
var fs = require('fs');
var dir = '/log_folder';

if (!fs.existsSync(dir)){
    fs.mkdirSync(dir);
}

Question: How do I URl Encode in Node.js?
for this, you can use encodeURIComponent (JS function)
encodeURIComponent('select * from table where i()')



Question: How do POST data in an Express JS?
for this, you must install express using "npm install express"
var express = require('express') , app = express.createServer();
app.use(express.bodyParser());
app.post('/', function(request, response){
  console.log(request.body);      
  response.send(request.body);    
});
app.listen(3008);




Question: How to output pretty html in Express?
for this, you must install express using "npm install express"
app.set('view options', { pretty: true });



Question: How to setup cron in NodeJS?
https://github.com/kelektiv/node-cron



Question: How to setup Logging in NodeJS?
  1. Install log4js
    npm install log4js
    
  2. Configuraiton ./config/log4js.json)
    {"appenders": [
        {
            "type": "console",
            "layout": {
                "type": "pattern",
                "pattern": "%m"
            },
            "category": "app"
        },{
            "category": "test-file-appender",
            "type": "file",
            "filename": "log_file.log",
            "maxLogSize": 10240,
            "backups": 3,
            "layout": {
                "type": "pattern",
                "pattern": "%d{dd/MM hh:mm} %-5p %m"
            }
        }
    ],
    "replaceConsole": true }
  3. Log data
    var log4js = require( "log4js" );
    log4js.configure( "./config/log4js.json" );
    var logger = log4js.getLogger( "test-file-appender" );
    logger.debug("Hello");//debug 
    logger.info("Info logs"); //info
    logger.error("Error logs") //error
    

Question: How redis works with NodeJS?
for this, you must install Redis
npm install redis

Include redis in code
redis = require('redis');

Create Redis object
var clientRedis = redis.createClient('6379', '127.0.0.1');

Save the data in Redis
clientRedis.hset("users", '10', 'roberts');  //Name, key, value

Delete the data from redis
clientRedis.del("users", 10);



Question: How to get current date in Nodejs?
new Date().toISOString();// '2016-11-04T14:51:06.157Z'

Friday, 17 March 2017

Node js Tutorial for beginners with examples - page 4

Node js Tutorial for beginners with examples - page 4

Question: How to print a stack trace in Node.js?
console.trace("print me")



Question: How can I get the full object in Node.js's console.log()?
const util = require('util');
console.log(util.inspect(myObject, false, null))



Question: How to use jQuery with Node.js?
First instal the jquery then use as following.
require("jsdom").env("", function(err, window) {
    if (err) {
        console.error(err);
        return;
    }

    var $ = require("jquery")(window);
});



Question: How to change bower's default components folder?
Create a .bowerrc file in root and add following code.
{
  "directory" : "public/components"
}



Question: How to encode base64 in nodeJS?
console.log(new Buffer("hello").toString('base64')); //aGVsbG8=



Question: How to decode base64 in nodeJS?
console.log(new Buffer("aGVsbG8=", 'base64').toString('ascii')); //hello



Question: How to get listing of files in folder?
const testFolder = './files/';
const fs = require('fs');
fs.readdir(testFolder, (err, files) => {
  files.forEach(file => {
    console.log(file);
  });
})



Question: How do you extract POST data in Node.js?
app.use(express.bodyParser());
app.post('/', function(request, response){
    console.log(request.body.user.fname);  //print first name
    console.log(request.body.user.lname); //print last name
});



Question: How to remove file nodeJS?
var fs = require('fs');
var filePath = '/folder/arun.docx'; 
fs.unlinkSync(filePath);



Question: How to access the GET parameters after ? in Express?
var email = req.param('email');


Question: How to copy file in nodeJS?
var fs = require('fs');
fs.createReadStream('existing.txt').pipe(fs.createWriteStream('new_existing.txt'));



Question: How to append string in File?
var fs = require('fs');
fs.appendFile('message.txt', 'data to append', function (err) {

});



Question: How to get version of package?
var packageJSON = require('./package.json');
console.log(packageJSON.version);



Question: What is express js?
Express.js is a NodeJS framework.
It is designed for building single-page, multi-page, and hybrid web applications.


Question: How to Send emails in Node.js?
You can use node-email-templates.
https://github.com/crocodilejs/node-email-templates


Question: How to get Ip Address of client?
request.connection.remoteAddress