Node.js

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

Coding in Node.js can be challenging and getting used to the intricacies of Node.js code can be quite confusing. This collection of Node.js code  examples is aimed at helping you perform common Node.js functions. No matter your experience level, from beginner to advanced, the following Node.js sample code will be useful for all developers. 

If you are a Node.js Developer, add all of the following Node.js snippets to Pieces for some extreme time-saving shortcuts. 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.

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

How to Create a HTTP Server in Node.js

This Node.js code snippet creates a simple Node.js 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');

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

Node.js Parse command-line arguments

This basic Node.js code is used 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);

tags: node.js, javascript, sleep, settimeout

How to use Sleep in Node.js

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

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

Tags: node.js, javascript, assert

How to use the Assert function in Node.js

The Assert Node.js example below uses the assert module to provide a set of assertion functions for verifying invariants.

const assert = require('assert');

assert(5 > 7);

Tags: node.js, javascript, cpu

Getting the information of all CPUs installed

Converts JSON into an object.

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

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

Tags: node.js, javascript, json

How to Store JSON in a File using Node.js

This Node.js code, given a data object, converts the object to a JSON string and stores 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)
  }
}

Tags: node.js, javascript, HTTP

How to get data out of an HTTP Get Request using Node.js code snippets

This simple Node.js code is used 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();

Tags: node.js, javascript, buffer

How to compare Two Buffers Using Node.js

Add this Node.js source code to compare two buffer objects and return 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);

Tags: node.js, javascript, static file server

How to Create a static file server in Node.js

In this Node.js code example you request a given 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);

Tags: node.js , javascript, events

How to use Event emitter in Node.js

In the following Node.js sample code, 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

Tags: node.js, javascript, query string

How to Parse URLs in Node.js

This sample Node.js code allows 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);

Tags: node.js, javascript

How to Create an empty file using Node.js

This example Node.js code creates 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!');
	});
};

Tags: node.js, javascript

How to Convert a path from relative to absolute path in Node.js

This Node.js source code 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);

Tags: node.js, javascript

How to Update an existing file in Node.js

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!');
	});
};

Tags: node.js, javascript

How to perform a Runtime environment check using Node.js

This simple Node.js code checks if the current runtime environment is a browser.

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

Tags: node.js, javascript

How to Replace the existing content in a file in Node.js

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!');
	});
}

Tags: node.js, javascript, stream

How to Create a writable stream in Node.js

These Node.js code snippets 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);

Want to use these Dart code samples in your IDE? Download our JetBrains plugin or VSCode extension to improve your developer productivity wherever you code.

Let us know what you think! Would you like to see other Dart snippets not listed on this page? Suggest a collection you'd like to see to help other developers speed up their workflows.

Tags: node.js, javascript, stream

How to create a readable stream in Node.js

This sample Node.js code 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);

Tags: node.js, javascript

How to get the home directory of the current user in Node.js

This simple Node.js code is used to get the home directory of the current user.

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

Tags: node.js, javascript

How to read and parse a CSV file using Node.js

This simple Node.js code is used to get the home directory of the current user.

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);
		})
}

150,000+ Installs

Want to use these Node.js code snippets in your IDE?

Install one of our IDE integrations to 10x your productivity during your next coding project.