Node.js

If you want to take full advantage of Node.js, these are some of the most useful snippets for backend development.

Add to Pieces

When downloading this collection to Pieces, developers will receive relevant tags for easy and fast search in Pieces, a description for context, and related links.

Create a Node HTTP Server

Tags: node.js, javascript, node server, web server

Creates a simple HTTP server that writes a response to the client and listens on port 8080. If it is running, a message will be logged stating server running on port 8080.

const http = require('http');

http.createServer((request, response) => {

	response.writeHead(200, {
		'Content-Type': 'text/plain'
	});
	response.write('Hello from Pieces!');
	response.end();

}).listen(8080);

console.log('server running on port 8080'); 

Related links:

  1. https://zetcode.com/javascript/http/
  2. https://www.w3schools.com/nodejs/nodejs_http.asp
  3. https://nodejs.dev/learn/build-an-http-server

Parse command-line arguments

Tags: node.js, javascript, command-line arguments

To grab specified command-line arguments, we use the process module which gives control over the current Node.js process, and we remove the first two arguments from the command-line, the Node.js executable and the executed file name.

const getCmdArguments = () => process.argv.slice(2); 

Related links:

  1. https://nodejs.org/en/knowledge/command-line/how-to-parse-command-line-arguments/
  2. https://stackoverflow.com/questions/4351521/how-do-i-pass-command-line-arguments-to-a-node-js-program/4351548#4351548
  3. https://www.geeksforgeeks.org/node-js-process-argv-property/

Sleep

Implementing sleep functionality in Node.js using setTimeout along with a dynamic argument specifying time to wait.

Tags: node.js, javascript, sleep, setTimeout

const sleep = ms => new Promise( res => setTimeout(res, ms)); 

Related links:

  1. https://nodejs.org/dist./v8.12.0/docs/api/assert.html
  2. https://www.geeksforgeeks.org/node-js-assert-function/

Assert

Uses the assert module to provide a set of assertion functions for verifying invariants.

const assert = require('assert');

assert(5 > 7); 

Related links:

  1. https://nodejs.org/dist./v8.12.0/docs/api/assert.html
  2. https://www.geeksforgeeks.org/node-js-assert-function/

Getting the information of all CPUs installed

Get information about all CPUs available using the os module.

const os = require('os');
const value =  os.cpus();

console.log("os.cpus() ==> " + JSON.stringify(value) ); 

Related links:

  1. https://www.geeksforgeeks.org/node-js-os-cpus-method/
  2. https://nodejs.dev/learn/the-nodejs-os-module
  3. https://medium.com/analytics-vidhya/os-module-in-nodejs-26459c17f5a

Store JSON in a File

Tags: node.js, javascript, json

Given a data object, convert the object to a JSON string and store it in a file with the specified path.

const fileSystem = require('fs')

const storeData = (data, path) => {
  try {
    fileSystem.writeFileSync(path, JSON.stringify(data))
  } catch (error) {
    console.error(error)
  }
} 

Related links:

  1. https://flaviocopes.com/how-to-save-json-object-to-file-nodejs/

Get data out of an HTTP Get Request

Tags: node.js, javascript, HTTP

To get the data out of a Node.js HTTP get request with JavaScript, we can listen for the data event on the response and append it until the response has ended.

const callback = (response) => {
	let str = "";
	response.on("data", (chunk) => {
		str += chunk;
	});

	response.on("end", () => {
		console.log(str);
		// ...
	});
};

const request = http.request(options, callback).end(); 

Compare Two Buffers

Tags: node.js, javascript, buffer

Compares two buffer objects and returns a number defining their differences and can be used to sort arrays containing buffers.

const buffer1 = Buffer.from('abc');
const buffer2 = Buffer.from('abc');

let x = Buffer.compare(buf1, buf2);
console.log(x); 

Related links:

  1. https://masteringjs.io/tutorials/node/buffer-compare
  2. https://www.geeksforgeeks.org/node-js-buffer-compare-method/
  3. https://www.w3schools.com/nodejs/met_buffer_compare.asp

Create a static file server

Tags: node.js, javascript, static file server

Given a requested URL, the static file server will listen for requests and try to find a file on the local filesystem. If no file is found or it doesn’t exist, it returns a 404 error. The http module creates the server that listens on port 8000.

const fileSystem = require('fs');
const http = require('http');

http.createServer((request, response) => {
	fileSystem.readFile(__dirname + request.url, (error, data) => {
		if (error) {
			response.writeHead(404, {
				'Content-Type': 'text/html'
			});
			response.end('404: File not found');
		} else {
			response.writeHead(200, {
				'Content-Type': 'text/html'
			});
			response.end(data);
		}
	});
}).listen(8000); 

Related links:

  1. https://nodejs.org/en/knowledge/HTTP/servers/how-to-serve-static-files/
  2. https://www.tutorialsteacher.com/nodejs/serving-static-files-in-nodejs#:~:text=In your node application%2C you,module using NPM as below.&text=After installing node-static module,static file server in Node.
  3. https://www.geeksforgeeks.org/how-to-create-a-simple-web-server-that-can-read-a-given-file-on-a-given-disk-via-readfile-function/

Event emitter

Tags: node.js , javascript, events

The event module includes an EventEmitter class that can be used to raise and handle custom events.

const myEmitter = new EventEmitter();

function c1() {
	console.log('an event occurred!');
}

function c2() {
	console.log('yet another event occurred!');
}

myEmitter.on('eventOne', c1); // Register for eventOne
myEmitter.on('eventOne', c2); // Register for eventOne 

Related links:

  1. https://www.freecodecamp.org/news/how-to-code-your-own-event-emitter-in-node-js-a-step-by-step-guide-e13b7e7908e1/
  2. https://www.tutorialsteacher.com/nodejs/nodejs-eventemitter

Parse URLs

Tags: node.js, javascript, query string

Allow URLs to be parsed using the URL module which makes different parts of a URL available as object attributes

const URL = require('url').URL;

const createParseableURL = url => new URL(url); 

Related links:

  1. https://nodejs.org/api/url.html#whatwg-api
  2. https://www.nodebeginner.org/blog/post/nodejs-tutorial-whatwg-url-parser/

Create an empty file

Tags: node.js, javascript

Create an empty file using the open method

const fileSystem = require('fs');

const createFile = fileName => {
	fileSystem.open(fileName, 'w', error => {
		if (error) throw error;
		console.log('Saved!');
	});
}; 

Related links:

  1. https://flaviocopes.com/how-to-create-empty-file-node/
  2. https://www.w3schools.com/nodejs/nodejs_filesystem.asp#:~:text=ADVERTISEMENT-,Create Files,-The File System

Convert relative to absolute path

Tags: node.js, javascript

Helps convert a relative path to an absolute path by replacing the start of the path with the home directory.

const path = require("path"); 
const resolvePath = relativePath => path.resolve(relativePath);  

Related links:

  1. https://thewebdev.info/2022/05/23/how-to-convert-relative-path-to-absolute-with-node-js-2/
  2. https://www.cloudhadoop.com/nodejs-convert-relative-absolute/
  3. https://stackoverflow.com/a/38829194/10798834

Update an existing file

Tags: node.js, javascript

Add to an existing file’s contents without overwriting the file and only updating at the end.

const fileSystem = require('fs');

const updateFile = (fileName, text) => {
	fileSystem.appendFile(fileName, text, (error) => {
		if (error) throw error;
		console.log('Updated the file!');
	});
};  

Runtime environment check

Tags: node.js, javascript

Checks if the current runtime environment is a browser.

const isBrowser = () => ![typeof window, typeof document].includes('undefined'); 

Related links:

  1. https://www.w3resource.com/javascript-exercises/fundamental/javascript-fundamental-exercise-203.php
  2. https://techwatch.dev/snippet/determine-if-the-current-runtime-is-a-browser-in-nodejs-application

Replace the existing content in a file

Tags: node.js, javascript

Uses the writeFile method to replace a string in a file.

const fileSystem = require('fs');
const editFile = (fileName, text) => {
	fileSystem.writeFile(fileName, text, (error) => {
		if (error) throw error;
		console.log('Replaced the file!');
	});
} 

Related links:

  1. https://thewebdev.info/2022/02/26/how-to-replace-a-string-in-a-file-with-node-js/
  2. https://riptutorial.com/node-js/example/1608/writing-to-a-file-using-writefile-or-writefilesync
  3. https://stackoverflow.com/a/14181136/10798834

Create a writable stream

Tags: node.js, javascript, stream

Read chunks of data from an input stream and write to the destination using write(). The function returns a boolean value indicating if the operation was successful.

const http = require('http');
const fileSystem = require('fs');

http.createServer((request, response) => {
	// This opens up the writeable stream to `output`
	const writeStream = fileSystem.createWriteStream('./output');

	// This pipes the POST data to the file
	request.pipe(writeStream);

	// After all the data is saved, respond with a simple html form so they can post more data
	request.on('end', function() {
		response.writeHead(200, {
			"content-type": "text/html"
		});
		response.end('[-- Insert generic html FORM element here --]');
	});

	// This is here incase any errors occur
	writeStream.on('error', function(err) {
		console.log(err);
	});
}).listen(8080); 

Related links:

  1. https://nodesource.com/blog/understanding-streams-in-nodejs/
  2. https://nodejs.org/en/knowledge/advanced/streams/how-to-use-fs-create-write-stream/
  3. https://www.freecodecamp.org/news/node-js-streams-everything-you-need-to-know-c9141306be93/#:~:text=To implement a readable stream,way to implement readable streams.

Create a readable stream

Tags: node.js, javascript, stream

Initializes a readable stream that data can be sent to.

const stream = require('stream');
const readableStream = new Stream.Readable();
const pushToStream = text => readableStream.push(text); 

Related links:

  1. https://nodejs.dev/learn/nodejs-streams
  2. https://nodesource.com/blog/understanding-streams-in-nodejs/
  3. https://www.freecodecamp.org/news/node-js-streams-everything-you-need-to-know-c9141306be93/#:~:text=To implement a readable stream,way to implement readable streams.

Get home directory of the current user

Tags: node.js, javascript

Used to get the home directory of the current user.

const os = require('os');
const value =  os.homedir();
console.log("os.homedir() => " + value); 

Related links:

  1. https://www.geeksforgeeks.org/node-js-os-homedir-method/
  2. https://nodejs.org/api/os.html#oshomedir

Read a CSV file

Tags: node.js, javascript, csv

Read a csv file from a file path using the fs module and a comma as a delimiter.

const fileSystem = require("fs");
const { parse } = require("csv-parse");

const readCSV = filePath => {
	fileSystem.createReadStream(filePath)
		.pipe(parse({
			delimiter: ",",
			from_line: 2
		}))
		.on("data", function(row) {
			console.log(row);
		})
} 

Related links:

  1. https://www.digitalocean.com/community/tutorials/how-to-read-and-write-csv-files-in-node-js-using-node-csv
  2. https://csv.js.org/parse/
  3. https://stackoverflow.com/questions/23080413/parsing-a-csv-file-using-nodejs