Sunday, March 1, 2020

Node.JS development quick tips

1. use the backtick character (`) for string interpolation
const mystring='Dan Test'

console.log(`my string value is ${mystring}`);

output is "my string value is Dan Test"

2. @hapi/joi is great library to support JavaScript object validation.

you can find the example in the github.

https://github.com/hapijs/joi/blob/master/API.md

3.  fs.watch event will trigger twice when you change the file in the windows development environment. However fs.watchFile only fire once.

trigger twice

fs.watch(filename, ()=>console.log(`File ${filename} changed`));

fire properly

fs.watchFile(filename, ()=>{
    const ls=spawn('ls',['-l''-s'filename]);
    ls.stdout.pipe(process.stdout);
});

4. keyword const is for variable that has value assignment on declaration and will not change after the declaration. keywork let will  allow variable to be assigned a value more than once.

5. it is the best practice to use try and catch to handle the exception, since the program will be halt by uncaught exception.

6. const fs=require('fs') which will reference the file system library. node.js use require to import library.

7. use npm init -y to create a default package.json file for the project.

8. use npm install --save-dev( for project level development) --save-exact(will install the specified version only).

9. use + (unary plus to cast the result as a number)
book.id=+$('pgterms\\:ebook').attr('rdf:about').replace('ebooks/','');

10. Morgan module is great logging utility for debugging.

npm install morgan@latest to add this module to the project

the output will display as below

GET /hello/:Danny 200 9.785 ms - 18
GET /favicon.ico 404 2.592 ms - 24
GET /hello/:Danny 304 1.844 ms - -


11. use app.use() to specify middleware for the app.

app.use(morgan('dev')) to add morgan logging middleware to the app. 

12. use curl -i url to show the response body and  http header as well.

13. curl -s url will use the slient mode and only body will be displayed.









No comments:

Post a Comment