Thursday, April 13, 2017

Node js Tutorial for beginners with examples

Question: How do I pass command line arguments? and how i get the arguments?
Pass argument through Command line

node main.js one two=three four

Script to read value from command line
process.argv.forEach(function (val, index, array) {
console.log(index + '=> ' + val);
});
Output
0=> node
1=> /data/node/main.js
2=> one
3=> two=three
4=> four



Question: How can we debug Node.js applications?
Install node-inspector
npm install -g node-inspector



Question: How to debug application through node-inspector
node-debug app.js



Question: What is the purpose of Node.js module.exports?
module.exports is the object that's run as the result of a require call.
file: main.js
var sayHello = require('./sayhellotoworld');
sayHello.run(); // "Hello World!"

sayhellotoworld.js
exports.run = function() {
console.log("Hello World!");
}



Question: How to exit in Node.js?
process.exit();

End with specific code.
process.exit(1);



Question: Read environment variables in Node.js?
process.env.ENV_VARIABLE



Question: How to pars a JSON String?
var str = '{ "name": "Web technology experts notes", "age": 98 }';
var obj = JSON.parse(str);



Question: How to get GET (query string) variables in Node.js?include the "url" module
var url = require('url');
var url_parts = url.parse(request.url, true);
var query = url_parts.query;
console.log(query);



Question: How to get GET (query string) variables in Express.js?
var express = require('express');
var app = express();

app.get('/', function(req, res){
res.send('id: ' + req.query.id);
});



Question: How to make ajax call in nodeJS?
var request = require('request');
request.post(
'http://www.example.com/action',
{ json: { name: 'web technology experts',age:'15' } },
function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body)
}
}
);
 
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
 
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'
 

No comments:

Post a Comment

lEARNING: SQL | WHERE Clause

SQL | WHERE Clause WHERE keyword is used for fetching filtered data in a result set. It is used to fetch data accord...