Node.js virtual environment builder for creating isolated Node.js environments
80
Cross-platform utility functions providing essential functionality for file operations, process execution, network requests, and system compatibility checks used throughout nodeenv.
Essential file system utilities for directory and file management with proper permissions and cross-platform compatibility.
def mkdir(path):
"""
Create directory with proper permissions.
Parameters:
path (str): Directory path to create
Creates directory with appropriate permissions for the platform.
Handles existing directories gracefully and ensures parent
directories are created as needed.
"""
def make_executable(filename):
"""
Make file executable on Unix-like systems.
Parameters:
filename (str): Path to file to make executable
Sets executable permissions on Unix-like systems (Linux, macOS).
No-op on Windows where executable permissions work differently.
Used for shell scripts and binary files in environments.
"""
def writefile(dest, content, overwrite=True, append=False):
"""
Write content to file with options.
Parameters:
dest (str): Destination file path
content (str): Content to write
overwrite (bool): Whether to overwrite existing files (default: True)
append (bool): Whether to append to existing files (default: False)
Writes content to file with control over overwrite behavior.
Used for creating activation scripts, configuration files,
and other text files in environments.
Handles encoding properly and creates parent directories
as needed.
"""Command execution utilities with logging, error handling, and cross-platform compatibility.
def callit(cmd, show_stdout=True, in_shell=False, **kwargs):
"""
Execute shell command with logging and error handling.
Parameters:
cmd (str or list): Command to execute
show_stdout (bool): Whether to display command output (default: True)
in_shell (bool): Whether to run command in shell (default: False)
**kwargs: Additional arguments passed to subprocess
Returns:
int: Command exit code
Executes commands with comprehensive logging and error handling:
- Command logging with proper argument escaping
- Output capture and display control
- Cross-platform shell execution
- Working directory and environment control
- Timeout support for long-running commands
Used for Node.js compilation, npm installation, and other
system operations during environment creation.
"""Network utilities for downloading files and handling HTTP requests with SSL configuration.
def urlopen(url):
"""
Open URL with SSL certificate handling.
Parameters:
url (str): URL to open
Returns:
file-like object: Response object for reading data
Opens HTTP/HTTPS URLs with proper SSL certificate handling:
- Respects global ignore_ssl_certs setting
- Handles SSL certificate validation
- Provides consistent interface across Python versions
- Used for downloading Node.js binaries and source code
"""Enhanced file operation utilities providing additional functionality beyond standard library.
def copytree(src, dst, symlinks=False, ignore=None):
"""
Enhanced directory tree copying with better error handling.
Parameters:
src (str): Source directory path
dst (str): Destination directory path
symlinks (bool): Whether to copy symlinks as symlinks (default: False)
ignore (callable): Function to ignore certain files (default: None)
Enhanced version of shutil.copytree with:
- Better error handling and reporting
- Cross-platform compatibility improvements
- Proper handling of special files and permissions
- Used for copying Node.js installations and directory structures
"""Text encoding and processing utilities for cross-platform compatibility.
def to_utf8(text):
"""
Convert text to UTF-8 encoding for cross-platform compatibility.
Parameters:
text (str or bytes): Text to convert
Returns:
str or bytes: UTF-8 encoded text
Handles text encoding conversion with fallback strategies:
- Unicode and ASCII text handling
- UTF-8 encoding detection and conversion
- Windows-specific encoding fallbacks (cp1252)
- Graceful handling of encoding errors
Used for processing text from various sources including
downloads, configuration files, and command output.
"""Terminal output utilities for controlling display and formatting.
def clear_output(out):
"""
Clear terminal output line.
Parameters:
out (file-like): Output stream to clear
Clears the current terminal line for progress updates and
dynamic output display. Used for showing download progress
and build status updates.
"""
def remove_env_bin_from_path(env, env_bin_dir):
"""
Remove environment bin directory from PATH.
Parameters:
env (str): PATH environment variable string
env_bin_dir (str): Environment bin directory path
Returns:
str: Updated PATH string with environment bin directory removed
Removes the environment's bin directory from PATH variable
to prevent conflicts during environment setup and cleanup.
"""System and platform detection utilities for cross-platform compatibility.
def is_x86_64_musl():
"""
Detect x86_64 musl systems (Alpine Linux, etc.).
Returns:
bool: True if running on x86_64 musl system
Detects musl-based Linux distributions that require
unofficial Node.js builds for compatibility.
"""
def is_riscv64():
"""
Detect RISC-V 64-bit architecture.
Returns:
bool: True if running on RISC-V 64-bit system
Detects RISC-V architecture that requires special
Node.js build handling and unofficial builds.
"""Enhanced archive extraction utilities with better error handling.
def tarfile_open(*args, **kwargs):
"""
Enhanced tarfile.open with better error handling.
Parameters:
*args: Arguments passed to tarfile.open
**kwargs: Keyword arguments passed to tarfile.open
Returns:
tarfile.TarFile: Opened tar file object
Wrapper around tarfile.open with enhanced error handling:
- Better error messages for corrupted archives
- Handling of incomplete downloads
- Cross-platform compatibility improvements
- Used for extracting Node.js source and binary archives
"""import nodeenv
# Create directory structure
nodeenv.mkdir('/path/to/environment/bin')
nodeenv.mkdir('/path/to/environment/lib')
# Write activation script
script_content = """#!/bin/bash
export NODE_VIRTUAL_ENV="/path/to/environment"
export PATH="$NODE_VIRTUAL_ENV/bin:$PATH"
"""
nodeenv.writefile('/path/to/environment/bin/activate', script_content)
nodeenv.make_executable('/path/to/environment/bin/activate')import nodeenv
# Execute build command
exit_code = nodeenv.callit(['make', '-j4'], show_stdout=True)
if exit_code != 0:
print(f"Build failed with exit code: {exit_code}")
# Execute with custom environment
exit_code = nodeenv.callit(
['npm', 'install', '-g', 'express'],
show_stdout=True,
env={'NODE_PATH': '/path/to/node_modules'}
)import nodeenv
# Download file with SSL handling
try:
response = nodeenv.urlopen('https://nodejs.org/dist/v18.17.0/node-v18.17.0.tar.gz')
data = response.read()
with open('node-source.tar.gz', 'wb') as f:
f.write(data)
except Exception as e:
print(f"Download failed: {e}")import nodeenv
# Handle text encoding
text_data = "Some text with special characters: café, naïve"
utf8_text = nodeenv.to_utf8(text_data)
print(f"UTF-8 encoded: {utf8_text}")import nodeenv
# Check platform capabilities
if nodeenv.is_x86_64_musl():
print("Using unofficial builds for musl system")
if nodeenv.is_riscv64():
print("Using unofficial builds for RISC-V system")
# Use platform flags
print(f"Python 3: {nodeenv.is_PY3}")
print(f"Windows: {nodeenv.is_WIN}")
print(f"Cygwin: {nodeenv.is_CYGWIN}")Install with Tessl CLI
npx tessl i tessl/pypi-nodeenvdocs
evals
scenario-1
scenario-2
scenario-3
scenario-4
scenario-5
scenario-6
scenario-7
scenario-8
scenario-9
scenario-10