-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathNotes
396 lines (316 loc) · 18.7 KB
/
Notes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
What is NodeJS?
-Node.js is an open-source and cross-platform JavaScript runtime environment. Node.js runs the V8 JavaScript engine, the core of Google Chrome, outside of the browser.
-A Node.js app is run in a single process, without creating a new thread for every request
-When Node.js performs an I/O operation, like reading from the network, accessing a database or the filesystem, instead of blocking the thread and wasting CPU cycles waiting, Node.js will resume the operations when the response comes back.
In practice, this means that for the time being you use require() in Node.js and import in the browser.
The V8 JavaScript Engine
-V8 is the name of the JavaScript engine that powers Google Chrome. It's the thing that takes our JavaScript and executes it while browsing with Chrome.
-JavaScript engine is independent of the browser in which it's hosted.
-The Node.js ecosystem is huge and thanks to it V8 also powers desktop apps, with projects like Electron.
Other JS engines
-Firefox has Spider Monkey
-Safari has javascript core also known as Nitro.
-Edge was basically built on Chakra( now rebuilt using Chromium and the V8 engine.)
-V8 is written in C++
Conclusion
-JavaScript is generally considered an interpreted language, but modern JavaScript engines no longer just interpret JavaScript, they compile it.
-JavaScript is internally compiled by V8 with just-in-time (JIT) compilation to speed up the execution.
Run Node.js scripts from the command line
-If your main Node.js application file is app.js, you can call it by typing:
$ node app.js
How to exit from a Node.js program?
-The process core module provides a handy method that allows you to programmatically exit from a Node.js program: process.exit().
-By default the exit code is 0, which means success,Different exit codes have different meaning
-You can also set the process.exitCode property:
$ process.exitCode = 1
-SIGKILL is the signal that tells a process to immediately terminate, and would ideally act like process.exit().
-SIGTERM is the signal that tells aprocess to gracefully terminate.It is the signal that's sent from process managers like upstart or supervisord and many others.
-You can send this signal from inside the program, in another function:
$ process.kill(process.pid, 'SIGTERM')
-Express is a framework that uses the http module under the hood, app.listen() returns an instance of http.
How to read environment variables from Node.js
-The process core module of Node.js provides the env property which hosts all the environment variables that were set at the moment the process was started.
$ process.env.NODE_ENV // "development"
------------------------------------------------------------------------
How to use the Node.js REPL (Read Evaluate Print Loop)
-To enter into REPL mode just type the node command.
$ node
-REPL also known as Read Evaluate Print Loop is a programming language environment(Basically a console window) that takes single expression as user input and returns the result back to the console after execution.
-REPL is interactive i.e it supports autocompletion when Tab is pressed.
-Number is class having various properties and methods in javascript.
-Acess to global objects on typing $ global. ("Now pressing tab")
Dot commands in REPL
-The REPL has some special commands, all starting with a dot .. They are:
.help: shows the dot commands help
.editor: enables editor mode, to write multiline JavaScript code with ease. Once you are in this mode, enter ctrl-D to run the code you wrote.
.break: when inputting a multi-line expression, entering the .break command will abort further input. Same as pressing ctrl-C.
.clear: resets the REPL context to an empty object and clears any multi-line expression currently being input.
.load: loads a JavaScript file, relative to the current working directory
.save: saves all you entered in the REPL session to a file (specify the filename)
.exit: exits the repl (same as pressing ctrl-C two times)
------------------------------------------------------------------------
Node.js, accept arguments from the command line
-You can pass any number of arguments when invoking a Node.js application using
$ node app.js
-Arguments can be standalone or key-value pairs:
$ node app.js joe
$ node app.js name==joepr
-----------------------------------------------------------------------
06-Sep-2021
Terminating a process in NodeJS
-The process core module provides a handy method that allows you to programmatically exit from a Node.js program: process.exit().
- The process core module doesnot require a require its automatically avialable.
- NodeJS when runs this line the process is immidiately forced to terminate.
Reading environment variables from NodeJS:
-The process core module of Node.js provides the env property which hosts all the environment variables that were set at the moment the process was started.
-Below code runs app.js and set USER_ID and USER_KEY
USER_ID=239482 USER_KEY=foobar node app.js
-A .env file also can be created incase we have to use mant environment variables, This file can be required as require('dotenv').config();
REPL Mode in NodeJS:
-Using REPL (Read Evaluate Print Loop), to get into REPL mode simply type "node" on the terminal
-REPL is an interactive programming language envoronment that takes a single expression as input and returns the result back to the console after execution.
-Exploring JS Objects and Global Objects:
1. Type any object in JS followed by a dot. The press tab, it will list all the methods/functions.
2. All global objects can ve accessed by typing 'global.' and then pressing tab.
-The special variable (_), entering _ in the node console prints out the result of the last expression.
Dot Commands:
.help: shows the dot commands help
.editor: enables editor mode, to write multiline JavaScript code with ease. Once you are in this mode, enter ctrl-D to run the code you wrote.
.break: when inputting a multi-line expression, entering the .break command will abort further input. Same as pressing ctrl-C.
.clear: resets the REPL context to an empty object and clears any multi-line expression currently being input.
.load: loads a JavaScript file, relative to the current working directory
.save: saves all you entered in the REPL session to a file (specify the filename)
.exit: exits the repl (same as pressing ctrl-C two times)
Argument variables in Node:
-Argument variables are specified as following:
node app.js name=lokesh age=26;
-Inside a node program the arguments are accessed using the argv property exposed by the process object.
-To see the list of argument variables:
process.argv.forEach(index, value){console.log(`${index} : ${value}`)}
-The first index is the location of node command.
-The second index stores the location of file.
-After these the argument variables are stored.
-To get the list of only argument variables :
const args = process.argv.slice(2);
OUTPUT to Command Line in NodeJS
-We can also format pretty phrases by passing variables and a format specifier.
%s format a variable as a string
%d format a variable as a number
%i format a variable as its integer part only
%o format a variable as an object
Eg : console.log('%o', Number);\
console.log('My name is %s and age is %d.','Lokesh',52)
Counting Elements
-Counts the number of times a string has been consoled.
-console.count('Lokesh')
-> arr.forEach(ele=>console.count(ele));
To reset counter
console.counterReset('string');
Printing Stack trace of a function:
->function trace() {console.trace()}
Count Time Spent
-Used to measure the time spent by function to execute.
- console.time(fnName) and console.timeEnd(fnName);
Eg:
const doSomething = () => console.log('test')
const measureDoingSomething = () => {
console.time('doSomething()')
//do something, and measure the time it takes
doSomething()
console.timeEnd('doSomething()')
}
measureDoingSomething()
stdout and stderr
-console method is used to print the stdout(standard output to the console.)
-console.error prints to the stderr stream, it will not appear in the console but will appear in the error log.
Colour the Output
-We can color the output of our text in the console by using escape sequences. An escape sequence is a set of characters that identifies a color.
-Eg : console.log('\x1b[33m%s\x1b[0m', 'hi!')
Other way of doing this by installing the Chalk library, it makes the code more readable.
npm install chalk
=> const chalk = require('chalk')
console.log(chalk.yellow('hi!'))
Accept Input from the command line in NOdeJs
-Node.js since version 7 provides the readline module to perform exactly this: get input from a readable stream such as the process.stdin stream, which during the execution of a Node.js program is the terminal input, one line at a time.
const readline = require('readline').createInterface({
input : process.stdin,
output : process.stdout
})
readline.question('What is your name',name=>{
console.log(`Hi ${name}`);
readline.close();
})
-A more complete and abstract solution is provided by the Inquirer.js package.
-> npm install inquirer
Expose functionality from a node.js file using exports.
-Functionalities can be imported from different files in nodejs, for importing require('') keyword is used.
-Two methods to export functionality.
1. The first is to assign an object to module.exports, which is an object provided out of the box by the module system, and this will make your file export just that object:
module.exports = objToBeExported
2. The second way is to add the exported object as a property of exports. This way allows you to export multiple objects, functions or data:
car = {model : 'i10', YOP : 2008}
exports.car = car;
OR Directly
exports.car = {model : 'i10', YOP : 2008}
Introduction to npm package manager
-npm is the standard package manager for nodejs
-It started as a way to download and manage dependencies of Node.js packages, but now it is used in frontend Javscript.
-npm manages downloads of dependencies of your project.
-Yarn and pnpm are alternatives to npm cli.
Installing all dependencies:
-npm install
-If a project has package.json file, npm will install all the dependencies required to run the apllication in node modeule directory, it creates the node_modules directory if it doesnot exists.
Installing Single dependencies:
-To install a single dependency:
npm install package_name
Versioning
-In addition to plain downloads, npm also manages versioning, so you can specify any specific version of a package, or require a version higher or lower than what you need.
Running tasks
-The package.json file supports a format for running command line tasks that can be run by using:
npm run <task-name>
npm run start-dev
npm run start
package.json file
{
"scripts": {
"start-dev": "node lib/server-development",
"start": "node lib/server-production"
}
}
Where does npm install the packages?
-There are two types of installation
1. Local
2. Global
-By default local installation takes place
Eg : npm install lodash
-Downloades dependencies and installs in node_modues
-Also adds lodash entry in dependencies property in package.json file.
-For global installation:
-npm install -g lodash
-To see global location on your machine
-npm root -g
Using/Executing a package installed by npm install
-To use a package, the package needs to be imported using the require command
Eg : const _ = require('lodash');
-To use an executable (Eg cowsay)
1. Traditional method:
-Go to node_modules/.bin/ and ececute ./cowsay "speech"
2. Using npx
npx cowsay 'speech'
package.json guide
-Properties of package.json file:
version indicates the current version
name sets the application/package name
description is a brief description of the app/package
main set the entry point for the application
private if set to true prevents the app/package to be accidentally published on npm
scripts defines a set of node scripts you can run
dependencies sets a list of npm packages installed as dependencies
devDependencies sets a list of npm packages installed as development dependencies
engines sets which versions of Node.js this package/app works on
browserslist is used to tell which browsers (and their versions) you want to support
Find installed version of an npm package;
-To see list of local npm packages installed:
-> npm list
-To see list of local npm packages installed:
->npm list -g
-To see only top level packages
-> npm list --depth=0
-To see version of a specific package
-> npm list <package_name>
-To see latest available version of a package
-> npm view packageName version
-To see all versions of a package in npm registry
->npm view packageName versions
Install older version of a package:
-To install a older version of package:
->npm install pachageName@version
npm install [email protected]
-To install a global version globally
->npm install -g packageName@version
Update all NodeJS dependencies to their latest version:
-Semantic Versioning (semver)
-1.5.0 - Major.Minor.Patch
-~1.5.0 - Only patch releases/updates are allowed.
-^1.5.0 - Minor and pathch updates are allowed.
- 1.5.0 - Fixed versions/ No updates.
-To update the dependencies
-> npm update
-To see list of outdated dependencies
-> npm outdated
-Some of the updates are major releases, and they are not updated after npm update, this is because a major release brings breaking changes.
-To update all the packages to a new major version install:
-> npm install -g npm-check-updates
-> ncu -u
-This will update all version hints in package.json file, to dependencics and dev dependecies, so that npm can install the new major version.
-> npm update
-If project is downloaded without node_modules
->npm install
Unisntalling npm packages
-To uninstall a package name:
-> npm uninstall <package_name>
-> npm uninstall -S
OR
->npm uninstall --save
-Removes reference from package.json file.
-To uninstall a global package
-> npm uninstall -g <package_name>
Local or Global packages
-Packges should be installed locally, this allows us to run different projects having different versions of dependencies together.
-A package should be installed globally when it provides an executeable command run from the shell, and is resued across projects.
Eg: npm
create-react-app
vue-cli
grunt-cli
mocha
react-native-cli
gatsby-cli
forever
nodemon
08 Sept 2021
npm dependencies and devDependencies
-When you are installing a dependency using npm install it is added to dependency property of package.json
-When you are installing a dependency using the following commands it will be add to devDependencies property of package.json
npm install -D
OR
npm install --save-dev
-Development Dependencies are intended only for development environment they are unneeded in production environmnet.
-npm install by default installs all devdependencies mentioned in package.json
-Use npm install --production to avoid installing development dependencies.
npx - Node.JS package runner
-Node.js developers used to publish most of the executable commands as global packages, in order for them to be in the path and executable immediately.
-This was a pain because you could not really install different versions of the same command.
-With npx different versions of executeable commannd can be run without installing them globally.3
Installation less command execution:
-you don't need to install anything
-you can run different versions of the same command, using the syntax @version
-> npx node@10 -v #v10.18.1
-> npx node@12 -v #v12.14.1
Node.JS Event Loop
-The Node.js JavaScript code runs on a single thread. There is just one thing happening at a time.
-It explains how Node.JS can be asyncronous having non-blocking I/O. Event loop are main reason behind the success of Node.JS
-The Node.js code runs on a Single Thread, i.e one thing is happening at a single time.
-In general, in most browsers there is an event loop for every browser tab, to make every process isolated and avoid a web page with infinite loops or heavy processing to block your entire browser.
Blocking Event Loop
-Any JavaScript code that takes too long to return back control to the event loop will block the execution of any JavaScript code in the page, even block the UI thread, and the user cannot click around, scroll the page, and so on.
-The call stack
-The call stack is a LIFO (Last In, First Out) stack.
-The event loop continuously checks the call stack to see if there's any function that needs to run.
Queuing function execution
-Let's see how to defer a function until the stack is clear.
-The use case of setTimeout(() => {}, 0) is to call a function, but execute it once every other function in the code has executed.
09 Sept 2021
The Message Queue
-When setTimeout() is called, the Browser or Node.js starts the timer. Once the timer expires, in this case immediately as we put 0 as the timeout, the callback function is put in the Message Queue.
-The loop gives priority to the call stack, and it first processes everything it finds in the call stack, and once there's nothing in there, it goes to pick up things in the message queue.
ES6 Job Queue
-ECMAScript 2015 introduced the concept of the Job Queue, which is used by Promises (also introduced in ES6/ES2015). It's a way to execute the result of an async function as soon as possible, rather than being put at the end of the call stack.
-Promises that resolve before the current function ends will be executed right after the current function.
-That's a big difference between Promises (and Async/await, which is built on promises) and plain old asynchronous functions through setTimeout() or other platform APIs.
Process.nextTick()
-Every time the event takes a full trip we call it a tick.
-Whenever we pass a function to Process.nextTick(), it instructs the JS engine to execute the function immidiately after the end of current operation in the current event loop, before the next event loop tick starts.
-A function passed to process.nextTick() is going to be executed on the current iteration of the event loop,after the current operation ends.
-It is a way by which we can tell the JS engine to process a function asyncronously (after current opereation), but as soon as possible not queue it.
-Calling setTimeout((),0) will instruct the JS engine to execute the function at the end of next Tick, much later than when using nextTick() which prioritises the call and executes the function before beginning of nextTick();
-Use nextTick() when you want to make sure that in the next event loop iteration that code is already executed.