5 One-Line Node.js Tricks Every Developer Should Know

Published on 30th March, 2025

Node.js is awesome because it lets us do so much with so little code. Sometimes, a single line is all you need to get the job done! In this post, I'll share five useful one-liners that can make your coding life easier. Each one comes with a simple example so you can see it in action. Let's dive in! 🚀


1. Run a Simple HTTP Server

Want to spin up a quick server without installing extra packages? Here's how:

require('http').createServer((_, res) => res.end('Hello World')).listen(3000);

Example:

Save this in a file like server.js and run it with:

node server.js

Now, open your browser and go to http://localhost:3000/, and you'll see "Hello World" displayed. 🎉


2. Get a Random Number Between Two Values

Need a random number? This one-liner does the trick:

const random = (min, max) => Math.random() * (max - min) + min;

Example:

console.log(random(10, 20)); // Outputs a random number between 10 and 20

Useful for generating random delays, test data, or game mechanics.


3. Remove Duplicates from an Array

Got an array with duplicates? Here's a quick way to filter them out:

const unique = (arr) => [...new Set(arr)];

Example:

console.log(unique([1, 2, 2, 3, 4, 4, 5])); // Output: [1, 2, 3, 4, 5]

No loops needed, just pure JavaScript magic! ✨


4. Check If an Object Is Empty

Want to check if an object has no keys? This will do it:

const isEmpty = (obj) => Object.keys(obj).length === 0;

Example:

console.log(isEmpty({})); // true
console.log(isEmpty({ name: 'Node.js' })); // false

Great for validating API responses or checking if a user submitted an empty form.


5. Read a File in One Line

Need to quickly read a file? Try this:

require('fs').readFileSync('file.txt', 'utf8');

Example:

Create a file.txt with some text, then run:

const data = require('fs').readFileSync('file.txt', 'utf8');
console.log(data); // Outputs the file content

Perfect for reading config files or small data files quickly.


Final Thoughts

These one-liners might be small, but they are powerful! Whether you're building a quick server, working with arrays, or handling files, these tricks can save you time and keep your code clean.

Comments

Please login to publish your comment!

By logging in, you agree to our Terms of Service and Privacy Policy.


No comments here!