Node.js: Difference between revisions
(49 intermediate revisions by the same user not shown) | |||
Line 1: | Line 1: | ||
= About node.js = | |||
* JavaScript is a programming language, and Node.js is a runtime environment that allows you to execute JavaScript code outside of a web browser. | |||
* https://nodejs.org/en/about/ As an asynchronous event-driven JavaScript runtime, Node.js is designed to build scalable network applications. In the example, many connections can be handled concurrently. Upon each connection, the callback is fired, but if there is no work to be done, Node.js will sleep. | |||
* https://www.javatpoint.com/nodejs-tutorial Node.js is a cross-platform environment and library for running JavaScript applications which is used to create networking and server-side applications. Node.js is mostly used to run real-time server applications. | |||
= Installation = | |||
See [[Javascript|Javascript]] | |||
= Tutorials = | |||
* https://www.w3schools.com/nodejs/default.asp | |||
* https://www.tutorialspoint.com/nodejs/index.htm | |||
* https://www.javatpoint.com/nodejs-tutorial | |||
* [https://youtu.be/TlB_eWDSMt4 Node.js Tutorial for Beginners: Learn Node in 1 Hour | Mosh] | |||
= node.js prompt = | = node.js prompt = | ||
== How to exit == | == How to exit == | ||
<pre> | <pre> | ||
.exit | brb@brb-P45T-A:~/Downloads$ node | ||
> Math.random() | |||
0.14142140373587608 | |||
> .exit | |||
</pre> | </pre> | ||
= http server = | = [http://en.wikipedia.org/wiki/HTTP HTTP] server = | ||
http://www.youtube.com/watch?v=jo_B4LTHi3I | http://www.youtube.com/watch?v=jo_B4LTHi3I | ||
Note HTTP is just one application of TCP. | |||
First create a js file | First create a js file | ||
Line 32: | Line 51: | ||
curl -i http://localhost:8000 | curl -i http://localhost:8000 | ||
</pre> | </pre> | ||
The output I get is | |||
<pre> | |||
$ curl -i http://localhost:8000 | |||
HTTP/1.1 200 OK | |||
Content-Type: text/plain | |||
Date: Sat, 19 Oct 2013 20:55:17 GMT | |||
Connection: keep-alive | |||
Transfer-Encoding: chunked | |||
Hello | |||
world | |||
</pre> | |||
We can compare this with the [http://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol#Example_session Example] from Hypertext Transfer Protocol in Wikipedia. | |||
== Test the http server == | == Test the http server == | ||
[[Linux#Apache_benchmark_.28ab.29_testing|Apache benchmark testing]] | |||
<pre> | <pre> | ||
ab -n 1000 -c 100 http://localhost:8000 | ab -n 1000 -c 100 http://localhost:8000 | ||
</pre> | </pre> | ||
= | == Setup Nginx as Frontend Server for Node.js == | ||
* [https://tecadmin.net/install-latest-nodejs-npm-on-ubuntu/ How to Install Latest Node.js and NPM on Ubuntu with PPA] | |||
* [https://tecadmin.net/setup-nginx-as-frontend-server-for-nodejs/ How to Setup Nginx as Frontend Server for Node.js] | |||
* [https://www.howtoforge.com/how-to-setup-nginx-as-frontend-server-for-nodejs-on-debian-10/ How to Install Node.js on Debian 10 and configure Nginx as a Frontend Proxy Server] (include PM2 installation) | |||
== PM2 == | |||
[https://www.makeuseof.com/how-to-install-and-set-up-pm2-on-linux-servers/ How to Install and Set Up PM2 on Linux Servers] | |||
= [http://en.wikipedia.org/wiki/Transmission_Control_Protocol TCP] server = | |||
== Simple example == | == Simple example == | ||
Create <tcp-server.js> file | Create <tcp-server.js> file | ||
Line 60: | Line 102: | ||
== Echo server == | == Echo server == | ||
This is modified from Simple server. | |||
<pre> | <pre> | ||
var net= require('net') | var net= require('net') | ||
Line 73: | Line 116: | ||
server.listen(8000); | server.listen(8000); | ||
</pre> | |||
We can use '''netstat -an | grep tcp''' to lists all the TCP ports on which your Linux server is listening including all the active network connections to and from your server. This can be very helpful in determining whether slowness is due to high traffic volumes: | |||
'''telnet''' needs to use Ctrl+] to break out the connection but '''nc''' can disconnect by using Ctrl+C. | |||
<pre> | |||
$ telnet localhost 8000 | |||
Trying 127.0.0.1... | |||
Connected to localhost. | |||
Escape character is '^]'. | |||
hello | |||
world | |||
klllkafda | |||
klllkafda | |||
^] | |||
telnet> quit | |||
Connection closed. | |||
$ | |||
$ nc localhost 8000 | |||
hello | |||
world | |||
adaf | |||
adaf | |||
^C | |||
$ | |||
</pre> | </pre> | ||
Line 105: | Line 175: | ||
Terminal 2: telnet localhost 8000 | Terminal 2: telnet localhost 8000 | ||
= http get = | |||
[https://www.tutorialspoint.com/nodejs/nodejs_restful_api.htm Node.js - RESTful API] from tutorialspoint.com | |||
<pre> | |||
$ cat hello-world-server.js | |||
setInterval(function() { | |||
console.log("world"); | |||
}, 2000) | |||
console.log("hello"); | |||
var http = require('http') | |||
setInterval(function() { | |||
console.log("fetching google.com"); | |||
http.get({ host: 'google.com' }, function(res) { | |||
console.log(res.headers); | |||
}); | |||
}, 2000) | |||
console.log("hello"); | |||
</pre> | |||
= Modules, npm and package.json = | |||
https://www.javatpoint.com/nodejs-package-manager | |||
<ul> | |||
<li>npm version # the packages are not complete? | |||
<pre> | |||
$ npm version | |||
{ npm: '6.9.0', | |||
ares: '1.15.0', | |||
brotli: '1.0.7', | |||
cldr: '35.1', | |||
http_parser: '2.8.0', | |||
icu: '64.2', | |||
modules: '64', | |||
napi: '4', | |||
nghttp2: '1.39.2', | |||
node: '10.16.3', | |||
openssl: '1.1.1c', | |||
tz: '2019a', | |||
unicode: '12.1', | |||
uv: '1.28.0', | |||
v8: '6.8.275.32-node.54', | |||
zlib: '1.2.11' } | |||
</pre> | |||
<li>npm install <Module Name> | |||
<pre> | |||
$ npm install tz | |||
npm WARN saveError ENOENT: no such file or directory, open '/Users/XXX/Downloads/package.json' | |||
npm notice created a lockfile as package-lock.json. You should commit this file. | |||
npm WARN enoent ENOENT: no such file or directory, open '/Users/XXX/Downloads/package.json' | |||
npm WARN Downloads No description | |||
npm WARN Downloads No repository field. | |||
npm WARN Downloads No README data | |||
npm WARN Downloads No license field. | |||
added 2 packages from 1 contributor and audited 2 packages in 0.904s | |||
found 0 vulnerabilities | |||
$ ls -lt | head | |||
# <package-lock.json> file & directory "node_modules" are created | |||
# there is no need to worry about the package-lock.json file | |||
</pre> | |||
<li>npm ls # List packages under ./node_modules | |||
<li>npm install -g <Module Name> # install packages in global environment | |||
<li>npm uninstall <Module Name> | |||
<li>npm search <Module Name> | |||
</ul> | |||
== require() == | |||
* https://nodejs.org/api/modules.html | |||
* os module. https://www.javatpoint.com/nodejs-os | |||
* dns module. https://www.javatpoint.com/nodejs-dns | |||
* net module for socket programming. https://www.javatpoint.com/nodejs-net | |||
* fs module for file system. https://www.javatpoint.com/nodejs-streams, https://www.javatpoint.com/nodejs-file-system | |||
* path module for file path. https://www.javatpoint.com/nodejs-path | |||
* assert module for testing. https://www.javatpoint.com/nodejs-assertion-testing | |||
* http module for creating a server. https://www.javatpoint.com/nodejs-web-modules | |||
* mysql module. | |||
== Global vs Local installation == | |||
[https://nodejs.org/en/blog/npm/npm-1-0-global-vs-local-installation/ npm 1.0: Global vs Local installation]. The rule of thumb is: | |||
* If you’re installing something that you want to use in your program, using require('whatever'), then install it locally, at the root of your project. | |||
* If you’re installing something that you want to use in your shell, on the command line or something, install it globally, so that its binaries end up in your PATH environment variable. | |||
== npm ls: check all the modules installed == | |||
https://nodejs.org/en/blog/npm/npm-1-0-the-new-ls/ | |||
<pre> | |||
$ npm ls # locally | |||
$ npm ls -g # globally | |||
</pre> | |||
== package.json == | |||
* https://docs.npmjs.com/files/package.json | |||
* package.json is present in the root directory of any Node application/module and is used to define the properties of a package. | |||
= Docker = | |||
[https://github.com/nodejs/docker-node Official Docker Image for Node.js] |
Latest revision as of 12:28, 13 September 2024
About node.js
- JavaScript is a programming language, and Node.js is a runtime environment that allows you to execute JavaScript code outside of a web browser.
- https://nodejs.org/en/about/ As an asynchronous event-driven JavaScript runtime, Node.js is designed to build scalable network applications. In the example, many connections can be handled concurrently. Upon each connection, the callback is fired, but if there is no work to be done, Node.js will sleep.
- https://www.javatpoint.com/nodejs-tutorial Node.js is a cross-platform environment and library for running JavaScript applications which is used to create networking and server-side applications. Node.js is mostly used to run real-time server applications.
Installation
See Javascript
Tutorials
- https://www.w3schools.com/nodejs/default.asp
- https://www.tutorialspoint.com/nodejs/index.htm
- https://www.javatpoint.com/nodejs-tutorial
- Node.js Tutorial for Beginners: Learn Node in 1 Hour | Mosh
node.js prompt
How to exit
brb@brb-P45T-A:~/Downloads$ node > Math.random() 0.14142140373587608 > .exit
HTTP server
http://www.youtube.com/watch?v=jo_B4LTHi3I
Note HTTP is just one application of TCP.
First create a js file
var http = require('http'); var s = http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); res.write('Hello \n'); setTimeout(function() { res.end("world\n"); }, 2000); }); s.listen(8000);
Then using node program to run the js script. We can test the program by using a web browser or curl program.
# Terminal 1 node web-server.js # Terminal 2 curl http://localhost:8000 OR use "-i" to include HTTP-header in the output curl -i http://localhost:8000
The output I get is
$ curl -i http://localhost:8000 HTTP/1.1 200 OK Content-Type: text/plain Date: Sat, 19 Oct 2013 20:55:17 GMT Connection: keep-alive Transfer-Encoding: chunked Hello world
We can compare this with the Example from Hypertext Transfer Protocol in Wikipedia.
Test the http server
ab -n 1000 -c 100 http://localhost:8000
Setup Nginx as Frontend Server for Node.js
- How to Install Latest Node.js and NPM on Ubuntu with PPA
- How to Setup Nginx as Frontend Server for Node.js
- How to Install Node.js on Debian 10 and configure Nginx as a Frontend Proxy Server (include PM2 installation)
PM2
How to Install and Set Up PM2 on Linux Servers
TCP server
Simple example
Create <tcp-server.js> file
var net= require('net') var server = net.createServer(function(socket) { socket.write('hello\n'); socket.end('world\n'); }); server.listen(8000);
After running this program, we can test it by using telnet or nc.
telnet localhost 8000 OR nc localhost 8000
Echo server
This is modified from Simple server.
var net= require('net') var server = net.createServer(function(socket) { socket.write('hello\n'); socket.write('world\n'); socket.on('data', function(data) { socket.write(data); }); }); server.listen(8000);
We can use netstat -an | grep tcp to lists all the TCP ports on which your Linux server is listening including all the active network connections to and from your server. This can be very helpful in determining whether slowness is due to high traffic volumes:
telnet needs to use Ctrl+] to break out the connection but nc can disconnect by using Ctrl+C.
$ telnet localhost 8000 Trying 127.0.0.1... Connected to localhost. Escape character is '^]'. hello world klllkafda klllkafda ^] telnet> quit Connection closed. $ $ nc localhost 8000 hello world adaf adaf ^C $
Chat server
net = require('net'); var sockets = []; var s = net.Server(function(socket) { sockets.push(socket); socket.on('data', function(d) { for(var i=0; i<sockets.length; i++) { if (sockets[i] == socket) continue; sockets[i].write(d); } }); socket.on('end', function() { var i = socksets.indexOf(socket); sockets.splice(i, 1); }); }); s.listen(8000);
Test it by
Terminal 1: telnet localhost 8000
Terminal 2: telnet localhost 8000
http get
Node.js - RESTful API from tutorialspoint.com
$ cat hello-world-server.js setInterval(function() { console.log("world"); }, 2000) console.log("hello"); var http = require('http') setInterval(function() { console.log("fetching google.com"); http.get({ host: 'google.com' }, function(res) { console.log(res.headers); }); }, 2000) console.log("hello");
Modules, npm and package.json
https://www.javatpoint.com/nodejs-package-manager
- npm version # the packages are not complete?
$ npm version { npm: '6.9.0', ares: '1.15.0', brotli: '1.0.7', cldr: '35.1', http_parser: '2.8.0', icu: '64.2', modules: '64', napi: '4', nghttp2: '1.39.2', node: '10.16.3', openssl: '1.1.1c', tz: '2019a', unicode: '12.1', uv: '1.28.0', v8: '6.8.275.32-node.54', zlib: '1.2.11' }
- npm install <Module Name>
$ npm install tz npm WARN saveError ENOENT: no such file or directory, open '/Users/XXX/Downloads/package.json' npm notice created a lockfile as package-lock.json. You should commit this file. npm WARN enoent ENOENT: no such file or directory, open '/Users/XXX/Downloads/package.json' npm WARN Downloads No description npm WARN Downloads No repository field. npm WARN Downloads No README data npm WARN Downloads No license field. + [email protected] added 2 packages from 1 contributor and audited 2 packages in 0.904s found 0 vulnerabilities $ ls -lt | head # <package-lock.json> file & directory "node_modules" are created # there is no need to worry about the package-lock.json file
- npm ls # List packages under ./node_modules
- npm install -g <Module Name> # install packages in global environment
- npm uninstall <Module Name>
- npm search <Module Name>
require()
- https://nodejs.org/api/modules.html
- os module. https://www.javatpoint.com/nodejs-os
- dns module. https://www.javatpoint.com/nodejs-dns
- net module for socket programming. https://www.javatpoint.com/nodejs-net
- fs module for file system. https://www.javatpoint.com/nodejs-streams, https://www.javatpoint.com/nodejs-file-system
- path module for file path. https://www.javatpoint.com/nodejs-path
- assert module for testing. https://www.javatpoint.com/nodejs-assertion-testing
- http module for creating a server. https://www.javatpoint.com/nodejs-web-modules
- mysql module.
Global vs Local installation
npm 1.0: Global vs Local installation. The rule of thumb is:
- If you’re installing something that you want to use in your program, using require('whatever'), then install it locally, at the root of your project.
- If you’re installing something that you want to use in your shell, on the command line or something, install it globally, so that its binaries end up in your PATH environment variable.
npm ls: check all the modules installed
https://nodejs.org/en/blog/npm/npm-1-0-the-new-ls/
$ npm ls # locally $ npm ls -g # globally
package.json
- https://docs.npmjs.com/files/package.json
- package.json is present in the root directory of any Node application/module and is used to define the properties of a package.