{"id":156,"date":"2020-11-30T19:23:00","date_gmt":"2020-11-30T19:23:00","guid":{"rendered":"https:\/\/molecularsciences.org\/content\/?p=156"},"modified":"2024-02-08T08:22:14","modified_gmt":"2024-02-08T13:22:14","slug":"node-js","status":"publish","type":"post","link":"https:\/\/molecularsciences.org\/content\/node-js\/","title":{"rendered":"Node.js"},"content":{"rendered":"\n<p><a href=\"https:\/\/nodejs.org\/\" target=\"_blank\" rel=\"noreferrer noopener\">Node<\/a>&nbsp;is an open source runtime environment for server-side applications. It allows you to run JavaScript on the server in addition to the browser. Almost all of the new and most widely used JavaScript solutions use Node in one form or another.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Installing Node.js<\/h3>\n\n\n\n<p>Download from&nbsp;<a href=\"https:\/\/nodejs.org\/\" target=\"_blank\" rel=\"noreferrer noopener\">https:\/\/nodejs.org<\/a>. Install with default options. To check, type the following on the terminal<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>$ which node<\/code><\/pre>\n\n\n\n<p>If you see a path like the following, nodejs is installed and you can start coding:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/usr\/local\/bin\/node<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">First Program<\/h3>\n\n\n\n<p>Type the following command in your non-formatting editor of choice such as sublimetext or nodepad++.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>console.log(\u201cHello World\u201d);<\/code><\/pre>\n\n\n\n<p>Save this file as hello.js. Type the following command to run the code:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>$ node hello.js<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">Process Object<\/h2>\n\n\n\n<p>The process object is available globally meaning that it can be accessed from anywhere in the code. It allows us to fetch information regarding the current process instance; information such as environmental variables, path, stdin, and stdout.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>console.log(process.argv);\n<\/code><\/pre>\n\n\n\n<p>Save this code as processdemo.js. To run:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>$ node processdemo.js\n<\/code><\/pre>\n\n\n\n<p>This code outputs the parameters used when the process starts. It&#8217;s output is as follows:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&#91; '\/usr\/bin\/node', '\/Users\/testing\/exercises\/processdemo.js' ]\n<\/code><\/pre>\n\n\n\n<p>If I run the command with parameters:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>$ node processdemo.js id name\n<\/code><\/pre>\n\n\n\n<p>The output will be:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&#91; '\/usr\/bin\/node', '\/Users\/testing\/exercises\/processdemo.js' ,'id','name']\n<\/code><\/pre>\n\n\n\n<p>To get an individual parameter, simply print the specific element in the process.argv array by it&#8217;s index<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>console.log(process.argv&#91;3]);\n<\/code><\/pre>\n\n\n\n<p>will output:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>name\n<\/code><\/pre>\n\n\n\n<p>process.stdout.write prints to the terminal. process.stdin.on adds a listener event. See the example below.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>var question = \"Say something?\";\nvar answer = \"\";\n\nfunction prompt() {\n  process.stdout.write(`\\n ${question}: `);\n}\n\nprocess.stdin.on('data', function(data) {\n  answer = data.toString().trim();\n  process.exit();\n});\n\nprocess.on('exit', function() {\n  process.stdout.write(`\\nYou said ${answer}\\n`);\n});\n\nprompt();\n<\/code><\/pre>\n\n\n\n<p>In this program, we begin from the call to prompt() function at the bottom. prompt() function prints the question to the terminal using stdout.write function(). process.stdin.on(&#8216;data&#8217;&#8230;) is an event listener that listens for data. Once you type something and hit return, process.on(&#8216;exit&#8217;..) function is called. It prints your response to the question.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Synchronous and Asynchronous Communication<\/h2>\n\n\n\n<p>Node support both synchronous and asynchronous communication. What is the difference? Synchronous communication is sequential communication. You can only run one job at a time and all jobs need to wait for their turn to run. In asynchronous communication, the jobs can run in parallel depending on available resources. Following is a simplified example.<\/p>\n\n\n\n<p>Suppose you call your Internet service provider and need to speak to a representative. You will be placed on hold until someone becomes available. This is synchronous communication. You are put on hold and you cannot do anything else. Some companies give you the option of a callback. You call in and leave a callback number. When a representative is free, he or she will call you back. You are free to do other things until you turn comes up. You are not on hold. This is asynchronous communication.<\/p>\n\n\n\n<p>In asynchronous programming, a callback is equivalent of function. It is called after a task is completed.<\/p>\n\n\n\n<p>Following code will synchronously list contents of a directory:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>fh = require(\u2018fs\u2019);\ncontent = fh.readdirSync(\u2018mydirectory\u2019);\nconsole.log(content);<\/code><\/pre>\n\n\n\n<p>Following code will asynchronously list contents of a directory<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>fh = require(\u2018fs\u2019);\ncontent = fh.readdir(\u2018mydirectory\u2019);\nconsole.log(content);<\/code><\/pre>\n\n\n\n<p>Except for the function name, the rest is the same.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Built-in Modules<\/h2>\n\n\n\n<p>A module encapsulates relate code, such as code for handling files, into a single unit of code. Node ships with many useful modules. These are called built-in modules. Programmers can create new modules. These are called custom modules.<\/p>\n\n\n\n<p>Following is a list of some built-in modules:<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Module<\/th><th>Description<\/th><\/tr><\/thead><tbody><tr><td>assert<\/td><td>used for unit testing<\/td><\/tr><tr><td>buffer<\/td><td>for handling binary data<\/td><\/tr><tr><td>crypto<\/td><td>for openssl<\/td><\/tr><tr><td>events<\/td><td>for event handling<\/td><\/tr><tr><td>fs<\/td><td>file handling<\/td><\/tr><tr><td>http<\/td><td>make Node.js act as an HTTP server<\/td><\/tr><tr><td>https<\/td><td>make Node.js act as an HTTPS server<\/td><\/tr><tr><td>net<\/td><td>create clients and servers<\/td><\/tr><tr><td>os<\/td><td>gives info about the os<\/td><\/tr><tr><td>path<\/td><td>handling file paths<\/td><\/tr><tr><td>querystring<\/td><td>handle url querystring<\/td><\/tr><tr><td>readline<\/td><td>handle readable streams<\/td><\/tr><tr><td>stream<\/td><td>handle streaming data<\/td><\/tr><tr><td>timers<\/td><td>timing functions like counting milliseconds<\/td><\/tr><tr><td>tls<\/td><td>for implementing TLS and SSL protocols<\/td><\/tr><tr><td>url<\/td><td>parsing URL strings<\/td><\/tr><tr><td>util<\/td><td>utility functions<\/td><\/tr><tr><td>zlib<\/td><td>To compress or decompress files<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<h4 class=\"wp-block-heading\">Assert<\/h4>\n\n\n\n<p>Following is a simple example of testing an expression:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>var assert = require('assert');\nassert(1 &gt; 10);<\/code><\/pre>\n\n\n\n<p>Since 1 not greater than 10, the assertion fails with the following error:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>assert.js:81\n  throw new assert.AssertionError({\n  ^\nAssertionError: false == true\n    at Object.&lt;anonymous&gt; (nodejs-ex\/assert.js:3:1)\n    at Module._compile (module.js:570:32)\n    at Object.Module._extensions..js (module.js:579:10)\n    at Module.load (module.js:487:32)\n    at tryModuleLoad (module.js:446:12)\n    at Function.Module._load (module.js:438:3)\n    at Module.runMain (module.js:604:10)\n    at run (bootstrap_node.js:389:7)\n    at startup (bootstrap_node.js:149:9)\n    at bootstrap_node.js:502:3<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\">Crypto<\/h4>\n\n\n\n<p>The crypto module offers many functions for encrypting and decrypting strings, streams, and buffers. Following example encrypts and decrypts a string:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>var cry = require('crypto'), algo = 'aes128', pass = 'UY675ygyf$$';\n\nfunction encrypt(txt){\n  var cipher = cry.createCipher(algo,pass)\n  var enc = cipher.update(txt,'utf8','hex')\n  enc += cipher.final('hex');\n  return enc;\n}\n\nfunction decrypt(txt){\n  var decipher = cry.createDecipher(algo,pass)\n  var dec = decipher.update(txt,'hex','utf8')\n  dec += decipher.final('utf8');\n  return dec;\n}\n\nvar mystring = encrypt(\"Encrypt me\")\nconsole.log(mystring);\nconsole.log(decrypt(mystring));<\/code><\/pre>\n\n\n\n<p>Output:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>e25c9392c7702ed52aef43ae0a48a78a\nEncrypt me<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">Streams<\/h2>\n\n\n\n<p>We have already seen how to read stdin (input from the terminal) as follows:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>console.log(process.stdin);<\/code><\/pre>\n\n\n\n<p>A program can take input from many different sources of streaming data. Readline module provides an interface to read data from any Readable stream including process.stdin. See&nbsp;<a target=\"_blank\" href=\"https:\/\/nodejs.org\/api\/readline.html\" rel=\"noreferrer noopener\">https:\/\/nodejs.org\/api\/readline.html<\/a>. Following is a simple example, I picked up from Readline documentation.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>const readline = require('readline');\n\nconst rl = readline.createInterface({\n  input: process.stdin,\n  output: process.stdout\n});\n\nrl.question('What do you think of Node.js? ', (answer) =&gt; {\n  console.log(`Thank you for your valuable feedback: ${answer}`);\n  rl.close();\n});<\/code><\/pre>\n\n\n\n<p>The first line requires the module. It is a core module so you don&#8217;t need to install anything using npm. The next block defines the input and output source for the interface. We specified stdin as data source and will output to stdout. The last block prompts a question and then prints the response in the console.<\/p>\n\n\n\n<p>Data can come from or go to many different sources such as text files, JSON, and XML. Streams are objects that allow you to read from or write to a data source.<\/p>\n\n\n\n<p>EventEmitters for streams are:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>Data: when data is available for reading<\/li><li>End : when there is no more data to read<\/li><li>Error: where there is an error read from or writing to a stream<\/li><li>Finish: when you are done using the stream<\/li><\/ul>\n\n\n\n<p>The following code show how to read from a file using these EventEmitters:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>var fs = require(\"fs\");\nvar content = '';\n\n\/\/ open file and create stream for reading\nvar rs = fs.createReadStream('in.txt');\n\n\/\/ read from the file\nrs.on('data', function(txt) {\n  console.log(txt);    \n  content += txt;\n  console.log(content);\n});\n\n\/\/ done reading\nrs.on('end', function(){\n  console.log('done reading');\n})\n\n\/\/ print any errors          \nrs.on('error', function(err){\n  console.log(err.stack);\n})   <\/code><\/pre>\n\n\n\n<p>Save this file as readfromfile.js. Create a text file, in.txt with the following contents and save in the same directory as readfromfile.js.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>one\ntwo\nthree<\/code><\/pre>\n\n\n\n<p>The output:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&lt;Buffer 6f 6e 65 0a 74 77 6f 0a 74 68 72 65 65&gt;\none\ntwo\nthree\ndone reading<\/code><\/pre>\n\n\n\n<p>Note that the first line output is the print out of the stream, so it is a buffer. When we assign the buffer to a text variable, it is converted to string data.<\/p>\n\n\n\n<p>Code to append to a file, simply use the following code<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>var fs = require(\"fs\");\nvar as = fs.appendFile('in.txt','four');<\/code><\/pre>\n\n\n\n<p>It appends the word four to the file. To write to a new file,<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>var fs = require(\"fs\");\nvar content = 'Four';\n\n\/\/ write stream to file\nvar ws = fs.createWriteStream('out.txt');\nws.write(content);\nws.end();\n\nws.on('error', function(err){\n  console.log(err.stack);\n});<\/code><\/pre>\n\n\n\n<p>This code writes the word Four in out.txt file. If the file does not exist, it will create it. If it exists, it will be overwritten. The following code pipes contents of an input file into an output file.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>var fs = require(\"fs\");\n\n\/\/ create read and write streams and pipe them\nvar rs = fs.createReadStream('in.txt');\nvar ws = fs.createWriteStream('out.txt');\nrs.pipe(ws);<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">Events<\/h2>\n\n\n\n<p>Node.js is an event-driven system. When you are performing different tasks, different events are emitted. You need to understand those events and how to use them. Events are defined by different modules. For example process.on() is an event. You can also create and use your own events. See example:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>var events = require('events');\nvar eventEmitter = new events.EventEmitter();\n\neventEmitter.on('bankrupt', function() {\n    console.log('You are bankrupt');\n});\n\nvar networth = -20000;\nif (networth &lt; 0) {\n    eventEmitter.emit('bankrupt');\n}<\/code><\/pre>\n\n\n\n<p>output:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>You are bankrupt<\/code><\/pre>\n\n\n\n<p>If the networth is less than 0, this event emitter prints a message to the console.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">File Management<\/h2>\n\n\n\n<p>Node uses the fs library to provide rich and powerful file management functionality. First let&#8217;s a directory and some files:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>$ mkdir data; cd data\n$ touch provinces.txt capitals.txt<\/code><\/pre>\n\n\n\n<p>Add the following text to provinces.txt<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Alberta\nBritish Columbia\nManitoba\nNew Brunswick\nNewfoundland and Labrador\nNova Scotia\nOntario\nPrince Edward Island\nQuebec\nSaskatchewan<\/code><\/pre>\n\n\n\n<p>Add the following to capitals.txt<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Charlottetown\nEdmonton\nFredericton\nHalifax\nOttawa\nQuebec\nRegina\nSt. John's\nToronto\nVictoria \nWinnipeg<\/code><\/pre>\n\n\n\n<p>Following code lists the files in a directory. It runs synchronously so not recommended for big files:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>var fs = require(\"fs\");\nvar files = fs.readdirSync(\".\/data\");\nconsole.log(files);<\/code><\/pre>\n\n\n\n<p>Output:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&#91; 'capitals.txt', 'provinces.txt' ]<\/code><\/pre>\n\n\n\n<p>The following code lists files in a directory asynchronously:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>var fs = require(\"fs\");\nfs.readdir('data',function(error, files) {\n    if (error) {\n        throw error;\n    }\n    console.log(files);\n});<\/code><\/pre>\n\n\n\n<p>output:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&#91; 'capitals.txt', 'provinces.txt' ]<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">Child Process<\/h2>\n\n\n\n<p>The child_process module allows you to communicate with other applications on your system by executing external processes in your environment. There are four kinds of child processes; exec(), spawn(), execFile(), fork(). I will be covering exec() and spawn() here. If a child process will execute once, use exec() function. For example the &#8220;cal&#8221; command on terminal prints the current month&#8217;s calendar in the terminal. The command is executed once, prints a result and that&#8217;s it. If a child process would be running for a long time and printing output several times, use spawn() function. An example would be:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>tail -f error_log<\/code><\/pre>\n\n\n\n<p>This command would keep running as long as apache is running and it would continue to print new entries in the error_log as they come.<\/p>\n\n\n\n<p>The following code opens a page in your default browser:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>var cp = require(\"child_process\").exec\nexec(\"open http:\/\/google.com\");<\/code><\/pre>\n\n\n\n<p>The following code runs a command in the terminal and displays its output:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>var cp = require(\"child_process\").exec;\ncp(\"node -v\", function(err, stdout) {\n    if (err) {\n        throw err;\n    }\n    console.log(\"Node version \");\n    console.log(stdout);\n});<\/code><\/pre>\n\n\n\n<p>This code runs the command &#8220;node -v&#8221; on the command line. This command returns the version of node installed on your system. This stdout output is then displayed by this program.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Create Server<\/h2>\n\n\n\n<p>The following code creates a server and assign a port.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>var http = require('http');\n\nhttp.createServer(function (req, res) {\n    res.writeHead(200, {'Content-Type': 'text\/plain'});\n    res.end('Your node server is running');\n}).listen(8282);\n<\/code><\/pre>\n\n\n\n<p>Simply run the code and open http:\/\/localhost:8282 in your browser.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Node&nbsp;is an open source runtime environment for server-side applications. It allows you to run JavaScript on the server in addition to the browser. Almost all of the new and most widely used JavaScript solutions use Node in one form or another. Installing Node.js Download from&nbsp;https:\/\/nodejs.org. Install with default options. To check, type the following on [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":417,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[185],"tags":[54,72],"class_list":["post-156","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-javascript","tag-javascript","tag-node-js"],"_links":{"self":[{"href":"https:\/\/molecularsciences.org\/content\/wp-json\/wp\/v2\/posts\/156","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/molecularsciences.org\/content\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/molecularsciences.org\/content\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/molecularsciences.org\/content\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/molecularsciences.org\/content\/wp-json\/wp\/v2\/comments?post=156"}],"version-history":[{"count":2,"href":"https:\/\/molecularsciences.org\/content\/wp-json\/wp\/v2\/posts\/156\/revisions"}],"predecessor-version":[{"id":418,"href":"https:\/\/molecularsciences.org\/content\/wp-json\/wp\/v2\/posts\/156\/revisions\/418"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/molecularsciences.org\/content\/wp-json\/wp\/v2\/media\/417"}],"wp:attachment":[{"href":"https:\/\/molecularsciences.org\/content\/wp-json\/wp\/v2\/media?parent=156"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/molecularsciences.org\/content\/wp-json\/wp\/v2\/categories?post=156"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/molecularsciences.org\/content\/wp-json\/wp\/v2\/tags?post=156"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}