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
stats.isDirectory().isSymbolicLink() (only valid with fs.lstat());

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

if (!fs.existsSync(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());'/', function(request, response){

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?

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"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', '');

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'

No comments :

Post a Comment