Skip to main content

5 posts tagged with "nodejs"

View All Tags

What is tmpdir() Function in Node.js

· One min read

In Node.js, the os module provides a method called tmpdir() which returns the operating system's default directory for temporary files.

Here's an example of how to use tmpdir() in a Node.js script:

const os = require("os");
const tmpdir = os.tmpdir();
console.log(tmpdir);

When you run this script, it will output the path to the temporary directory on your operating system. On most Unix-based systems (such as macOS and Linux), the default temporary directory is /tmp. On Windows, the default temporary directory is typically C:\Users\<username>\AppData\Local\Temp.

You can use the tmpdir() method to create temporary files or directories, such as for caching or storing intermediate results. Keep in mind that files in the temporary directory may be automatically deleted by the operating system at any time, so you should not rely on them for long-term storage.

What is the purpose of require.resolve() in Node.js?

· 2 min read

require.resolve() is a built-in method in Node.js that is used to resolve the module identifier to an absolute file path. It returns the path of the module if it exists, otherwise, it throws an error.

The purpose of require.resolve is to provide a way to check whether a module exists and to obtain the absolute path of that module. This is useful in situations where you need to programmatically determine the path of a module, such as when you want to load a plugin dynamically, or when you want to access the package.json file of a module.

require.resolve takes a single argument, which is the module identifier. This can be either a relative or an absolute path, or a module name that is installed in the Node.js node_modules directory.

Here's an example of how to use require.resolve to obtain the path of a module:

const path = require("path");

const modulePath = require.resolve("lodash");
console.log(modulePath); // Output: /path/to/project/node_modules/lodash/lodash.js

const relativePath = "./lib/myModule";
const resolvedPath = require.resolve(relativePath);
console.log(resolvedPath); // Output: /path/to/project/lib/myModule.js

In the example above, we used require.resolve to obtain the path of the lodash module installed in the node_modules directory, and the path of a module located in the project's lib directory.

Use ES Module Syntax to Import Node.js Modules like fs or https

· 2 min read

In Node.js each .js file is considered as a separate CommonJS module. That means if we declare a variable or function inside a file, we cannot access it from another file. We need to explicitly mention, what all variables and functions can be accessed by other files.

Import Core Node Modules in CommonJS Way

We know that Node.js comes with multiple modules like fs or https out of the box. If we need to use say, fs in our code, here is the syntax.

const fs = require("fs");

// Then use it like..
fs.readFileSync();

Import Core Node Modules in ES Module Way

If we are rewriting above code in ES Module way, it looks like this:

import * as fs from "fs";

fs.readFileSync();

Above syntax is one of the way in which we use import keyword. It takes all exported variables or functions from fs package and make it available for use.

Here are other ways we use import keyword.

import defaultExport from "module-name";
import * as name from "module-name";
import { export1 } from "module-name";
import { export1 as alias1 } from "module-name";
import { default as alias } from "module-name";
import { export1 , export2 } from "module-name";
import { export1 , export2 as alias2 , [...] } from "module-name";
import { "string name" as alias } from "module-name";
import defaultExport, { export1 [ , [...] ] } from "module-name";
import defaultExport, * as name from "module-name";
import "module-name";

You can read more in this MDN link.

How To Print Emoji in Node.js Console

· One min read

While running tools like yarn, we have seen emojis in Node.js console. If we want to print emojis in our project, node-emoji package can help. First, install it.

yarn add node-emoji

Then, we can use it like below:

var emoji = require("node-emoji");
console.log(emoji.get("coffee")); // ☕

A complete list of emojis present in the package can be viewed in this link https://raw.githubusercontent.com/omnidan/node-emoji/master/lib/emoji.json.

Now its time to play. Let me try a Merry Christmas!.

var emoji = require("node-emoji");

const christmas_tree = emoji.get("christmas_tree");
const santa = emoji.get("santa");
const tada = emoji.get("tada");
const sled = emoji.get("sled");
const bell = emoji.get("bell");
const confetti_ball = emoji.get("confetti_ball");

console.log(
`\n${christmas_tree}${bell} Merry Christmas! ${sled} ${tada} ${santa}\n`,
);

Here is the output:

Console emoji

How To Color Text in Terminal Using Node.js

· 2 min read

When we write console.log statement in our Node.js code, it is written in terminal. What if we need to change the color of printed text? To do that, we need to use ANSI escape codes.

console.log("\x1b[33m%s\x1b[0m", "I am in yellow color");

Above line prints the text in yellow color. We can even try the same line in browser console. The %s is replaced by the actual content. The \x1b[33m in the pattern gives yellow color to string. The pattern is an example of ANSI escape code which is a standardized code. Therefore, it works in any terminal.

Here is a set of codes to adjust text color, background color or text effects:

Reset = "\x1b[0m";
Bright = "\x1b[1m";
Dim = "\x1b[2m";
Underscore = "\x1b[4m";
Blink = "\x1b[5m";
Reverse = "\x1b[7m";
Hidden = "\x1b[8m";

FgBlack = "\x1b[30m";
FgRed = "\x1b[31m";
FgGreen = "\x1b[32m";
FgYellow = "\x1b[33m";
FgBlue = "\x1b[34m";
FgMagenta = "\x1b[35m";
FgCyan = "\x1b[36m";
FgWhite = "\x1b[37m";

BgBlack = "\x1b[40m";
BgRed = "\x1b[41m";
BgGreen = "\x1b[42m";
BgYellow = "\x1b[43m";
BgBlue = "\x1b[44m";
BgMagenta = "\x1b[45m";
BgCyan = "\x1b[46m";
BgWhite = "\x1b[47m";

If you are finding it difficult to use in the above format, there is a npm package colors for easy usage. Using that, we can print yellow colored text like below:

console.log("I am in yellow color".yellow);

When using colors package, we can chain effects. For example, to print yellow bold text in red background, we can use following code:

console.log("I am in yellow color".yellow.bgRed.bold);

Console text color