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.
How to Create a HTTP Server in Node.js
Tags: node.js, javascript, node server, web server
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');
Related links:
- Node HTTP tutorial
- Node.JS HTTP module
Node.js Parse command-line arguments
Tags: node.js, javascript, 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);
Related links:
- How do I pass command line arguments to a Node.js program
- The argy property
How to use Sleep in Node.js
Tags: node.js, javascript, sleep, setTimeout
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));
Related links:
- Sleep in Node.js
- How to add Node.js Sleep function example
How to use the Assert function in Node.js
Tags: node.js, javascript, assert
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);
Related links:
- Assert function in node.js
- Node.js assert function
Getting the information of all CPUs installed
Tags: node.js, javascript, cpu
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:
- Node.js os cpus method
- Node.js Documentation v19.7.0 - OS
- Using os module in NodeJS
How to Store JSON in a File using Node.js
Tags: node.js, javascript, json
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)
}
}
Related links:
- How to write a JSON object to file in Node.js
How to get data out of an HTTP Get Request using Node.js code snippets
Tags: node.js, javascript, HTTP
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();
Related links:
- 5 ways to make HTTP requests in Node.js
- How to get data out of a node.js HTTP get request
How to compare Two Buffers Using Node.js
Tags: node.js, javascript, buffer
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);
Related links:
- Compare Two Buffers in Node.js
- Node.js Buffer.compare() Method - Node.js Syntax
- Node.js Buffer.compare() Method - Node.js example code
How to Create a static file server in Node.js
Tags: node.js, javascript, static file server
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);
Related links:
- Serve Static Resources using Node-static Module
- How to create a simple web server that can read a given file on a given disk - readFile function
How to use Event emitter in Node.js
Tags: node.js , javascript, events
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
Related links:
- How to code your own event emitter in Node.js - a step-by-step guide
- Node.js EventEmitter example
How to Parse URLs in Node.js
Tags: node.js, javascript, query string
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);
Related links:
- Node.js WHATWG URL API
- Node.js tutorial - The WHATWG URL parser
How to Create an empty file using Node.js
Tags: node.js, javascript
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!');
});
};
Related links:
- How to create an empty file in Node.js
- Node.js File System Module
How to Convert a path from relative to absolute path in Node.js
Tags: node.js, javascript
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);
Related links:
- How to convert relative path to absolute with Node.js
- How to Convert Relative to Absolute path in Node.js
- NodeJS - convert relative path to absolute
How to Update an existing file in Node.js
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!');
});
};
Related links:
- Node.js File System module
- Update an existing file in Node.js
How to perform a Runtime environment check using Node.js
Tags: node.js, javascript
This simple Node.js code checks if the current runtime environment is a browser.
const isBrowser = () => ![typeof window, typeof document].includes('undefined');
Related links:
- JavaScript: Determine whether the current runtime environment is a browser
- Determine if the current runtime is a browser in Node.js application
How to Replace the existing content in a file in Node.js
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:
- How to replace a string in a file with Node.js
- Writing to a file using writeFile or writeFileSync - Node.Js example code
- Replace a string in a file with NodeJS
How to Create a writable stream in Node.js
Tags: node.js, javascript, stream
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);
Related links:
- Understanding Streams in Node.js
- Node.js: Everything you need to know - Implement a Readable Stream
How to create a readable stream in Node.js
Tags: node.js, javascript, stream
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);
Related links:
- Node.js Documentation v19.7.0 - Stream
- Understanding Streams in Node.js
- Node.js Streams: Everything you need to know - Implement a Readable Stream
How to get the home directory of the current user in Node.js
Tags: node.js, javascript
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);
Related links:
- Node.js os.homedir() Method
- Node.js Documentation v19.7.0 - os.homedir
How to read and parse a CSV file using Node.js
Tags: node.js, javascript, csv
This Node.js example code reads 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:
- How to Read and Write CSV Files in Node.js using Node-CSV
- CSV Parser for Node.js
- Parsing a CSV file using NodeJS
Want to use these Node.js code snippets in your integrated development environment or web browser? Download the best VS Code extension for Node.JS or the Pieces desktop app to improve your backend developer productivity.
Not seeing examples of Node.js code snippets that other developers would benefit from? Suggest a collection you’d like to see to help other developers speed up their workflows.