Sunteți pe pagina 1din 3

// Load view engine

app.set( 'view engine', 'ejs' );

// Load static files


app.use( express.static('public') )

--------------------------------------------------

Import your files


test.js
console.log("hello");

app.js
require('./test');

so when you call app.js


it will print "hello"

--------------------------------------------------
How browser has window and document objects
Simillarly node has global and process
on process there is property argv
(which contain all the arguments provided)

console.log(process.argv)

node app sam

then it will return array


[ 'C:\\Program Files\\nodejs\\node.exe',
'C:\\Users\\sambeet.sahoo.OM\\Desktop\\node\\app',
'Sam' ]

So if we write

console.log(process.argv[2])
it will always return, what the value we provided i.e "sam"

var command = process.argv[2];


if(command === "add"){
console.log("adding 2 nums");
}else if(command === "sub"){
console.log("sub 2 nums");
}

node app add


// "adding 2 nums"

ex-2
if we do something like this

console.log(process.argv);

node app add --title="cool"

[ 'C:\\Program Files\\nodejs\\node.exe',
'C:\\Users\\sambeet.sahoo.OM\\Desktop\\node\\app',
'add',
'--title=cool' ]

Then it will return 4 things

So now our turn is how to parse 4th argument in array


Node is always provide raw arguments

Yargs do it for you

npm i yargs

now load yargs to app and see how it behaves

const yargs = require('yargs');

console.log(process.argv);
console.log(yargs.argv);

node app

[ 'C:\\Program Files\\nodejs\\node.exe',
'C:\\Users\\sambeet.sahoo.OM\\Desktop\\node\\app' ]
{ _: [], '$0': 'app' }

Now do this

node app add --title="cool"


{ _: [ 'add' ], title: 'cool', '$0': 'app' }

Its quite cool and it parse title

----------------------------------

Setting up yargs

In the notes application


People should able to
1. add note
2. remove notes
3. read individual notes
4. list out all notes

Now create add commands, and node will execute by the commands

yargs.command({
command:'add',
describe:'add a new note',
handler: function(){
console.log("Adding a new note")
}
})
// create remove command
yargs.command({
command:'remove',
describe:'remove a new note',
handler: function(){
console.log("removing a new note")
}
})

// create list command


yargs.command({
command:'list',
describe:'list all notes',
handler: function(){
console.log("listing all notes")
}
})
// create read command
yargs.command({
command:'read',
describe:'read the note',
handler: function(){
console.log("reading the note")
}
})

console.log(yargs.argv);

node app remove


--removing a new note

and like this....

--------------------------------------------------
File system module

const fs = require('fs');
fs.writeFileSync('notes.txt',"Lorem ipsum eta...")
// this will create a file notes.txt and write 'Lorem ipsum eta...'

//appendFileSync:- used to append new text on the file

S-ar putea să vă placă și