JacobZwang
JacobZwang•4mo ago

use `process` without importing it

Is there a way to enable the global process variable without manually importing it from node:process? This would help a lot with making node projects compatible with deno without any code change.
3 Replies
Deno AI Helper
Deno AI Helper•4mo ago
In Deno, there is no global process variable as there is in Node.js. The documentation states that Deno does not add additional objects and variables to the global scope, other than the Deno namespace. Any API that doesn't exist as a web standard browser API will be found in this namespace. Therefore, to access functionalities similar to Node.js's process, you would use the Deno namespace in Deno. For example, the process.cwd() function in Node.js exists in Deno as Deno.cwd(). If you need to access environment variables, you would use Deno.env.get("VAR_NAME") instead of process.env.VAR_NAME. To make Node projects compatible with Deno without changing the code that relies on the process variable, you would need to create a compatibility layer that maps Node.js global objects to their Deno equivalents. However, this would involve some code changes, as there is no built-in mechanism in Deno to globally expose a process variable without importing it. 🦕
BowTiedGnome
BowTiedGnome•4mo ago
if the code in a node project, you can reference the process object using globalThis
const g = globalThis as Record<string, unknown>;
if (g.process) {
// do something with process
}
const g = globalThis as Record<string, unknown>;
if (g.process) {
// do something with process
}
jeff.hykin
jeff.hykin•4mo ago
If its a codebase you're importing you can make it a global manually. Main.js
// note this does need to be an import (can't inline) otherwise it won't run before the codebase import
import "enable_global_process.js"
import "./codebase/something.js"

console.log(process)
// note this does need to be an import (can't inline) otherwise it won't run before the codebase import
import "enable_global_process.js"
import "./codebase/something.js"

console.log(process)
enable_global_process.js
import process from "node:process"
globalThis.process = process
import process from "node:process"
globalThis.process = process