This directory contains practical TypeScript examples demonstrating SharpTS capabilities, from basic utilities to advanced interoperability with C#.
All examples can be run using the SharpTS interpreter:
sharpts Examples/<example-name>.ts [arguments]Or compiled ahead-of-time to .NET assemblies:
sharpts --compile Examples/<example-name>.ts
dotnet Examples/<example-name>.dll [arguments]What it does: Generates multiple checksums (MD5, SHA1, SHA256, SHA512) for any file.
Usage:
sharpts Examples/file-hasher.ts <filepath>
# Example
sharpts Examples/file-hasher.ts README.mdDemonstrates:
cryptomodule:createHash(),.update(),.digest()fsmodule:readFileSync(),existsSync(),statSync()pathmodule:basename(),resolve()- Command-line argument processing via
process.argv - String manipulation and formatting
- For-of loops with arrays
Key Features:
- Displays file size in human-readable format (B, KB, MB, GB)
- Validates file existence and type
- Computes four hash algorithms in one pass
- Clean tabular output
What it does: Automatically organizes files in a directory by moving them into categorized folders based on file extension (images, documents, code, archives, etc.).
Usage:
sharpts Examples/file-organizer.ts <directory> [--dry-run]
# Example - preview changes without moving files
sharpts Examples/file-organizer.ts ~/Downloads --dry-run
# Example - actually organize files
sharpts Examples/file-organizer.ts ~/DownloadsDemonstrates:
fsmodule:readdirSync(),statSync(),mkdirSync(),renameSync(),existsSync()pathmodule:join(),extname(),basename()- Object literals for mapping data
- Property access syntax with bracket notation
- Conditional logic and directory creation
- Safe "dry run" pattern for file operations
Key Features:
- Pre-configured categories for common file types
- Creates destination folders automatically
- Dry-run mode to preview changes
- Falls back to generic categorization for unknown extensions
- Skips files without extensions
- Summary statistics
What it does: Interactive password generator with customizable character sets and cryptographically secure randomness.
Usage:
sharpts Examples/password-generator.ts [length]
# Example - interactive mode
sharpts Examples/password-generator.ts
# Example - specify length upfront
sharpts Examples/password-generator.ts 24Demonstrates:
cryptomodule:randomBytes(),randomInt()readlinemodule:questionSync()for user input- String concatenation and character manipulation
- Interactive CLI with yes/no questions
- Input validation and error handling
- Mathematical calculations (entropy calculation using
Math.log())
Key Features:
- Generates 5 password options at once
- Customizable character sets (lowercase, uppercase, digits, symbols)
- Calculates password entropy in bits
- Validates password length (4-128 characters)
- Uses cryptographically secure random number generation
What it does: Displays comprehensive system information including OS details, memory usage, CPU info, and process metrics.
Usage:
sharpts Examples/system-info.tsDemonstrates:
osmodule:platform(),arch(),hostname(),cpus(),totalmem(),freemem(),homedir(),tmpdir(),userInfo(),type(),release()processmodule:pid,version,cwd(),env,argv,uptime(),memoryUsage()- Number formatting and calculations
- Working with arrays (CPU cores)
- Accessing object properties
- Environment variable access
- String truncation for display
Key Features:
- Memory statistics with percentage calculation
- CPU information (cores, model, speed)
- Process uptime formatting (hours, minutes, seconds)
- Selective environment variable display
- Human-readable memory sizes (GB and MB)
What it does: Parse, build, and manipulate URLs with an interactive command-line interface.
Usage:
# Parse a URL from command line
sharpts Examples/url-toolkit.ts "https://example.com/path?key=value"
# Interactive mode
sharpts Examples/url-toolkit.tsInteractive Commands:
parse <url>- Parse and display URL componentsencode <string>- URL encode a stringdecode <string>- URL decode a stringresolve <base> <rel>- Resolve a relative URL against a base URLbuild- Build a URL interactivelyquit- Exit
Demonstrates:
urlmodule:parse(),resolve()querystringmodule:parse(),stringify(),escape(),unescape()readlinemodule: Interactive input loops- String methods:
startsWith(),substring(),trim(),split() - Object key iteration with
Object.keys() - While loops and interactive REPL pattern
- Optional/nullable handling with
||operator
Key Features:
- Full URL parsing (protocol, host, port, pathname, query, hash)
- Query string parameter extraction
- Interactive URL builder
- URL encoding/decoding utilities
- Relative URL resolution
What it does: Comprehensive source code analysis tool that scans directories recursively and generates statistics about code files.
Usage:
sharpts Examples/SourceAnalyzer/source-analyzer.ts [directory] [--help]
# Example - analyze current directory
sharpts Examples/SourceAnalyzer/source-analyzer.ts
# Example - analyze specific directory
sharpts Examples/SourceAnalyzer/source-analyzer.ts ./src
# Example - show help
sharpts Examples/SourceAnalyzer/source-analyzer.ts --helpDemonstrates:
- TypeScript interfaces for type safety
- Complex directory traversal with recursion
- File filtering and pattern matching
- Multi-line string processing
- Advanced function detection heuristics
- Table formatting with padded strings
- Modular code organization with logical sections
- Process exit codes with
process.exit() - Path manipulation:
isAbsolute(),join()
Key Features:
- Supports multiple file types (.ts, .tsx, .js, .jsx, .css, .html, .json)
- Auto-excludes common directories (node_modules, .git, dist, build, obj, bin)
- Counts total lines, non-empty lines, and functions
- Function detection for multiple patterns (function keyword, arrow functions, class methods)
- Formatted table output with summary statistics
- Handles Windows reserved filenames safely
What it does: Demonstrates how to consume SharpTS-compiled TypeScript assemblies from C# applications using runtime reflection.
This is a more complex example with its own subdirectory structure and build process.
Structure:
Interop/
├── TypeScript/
│ └── Library.ts # TypeScript source with example classes
├── CompiledTS/ # Generated assemblies
│ ├── Library.dll # Compiled TypeScript (generated)
│ └── SharpTS.dll # Runtime dependency (copied)
├── Program.cs # C# consumer demonstrating interop
├── build.ps1 # Automated build script
├── README.md # Detailed interop documentation
└── SharpTS.Example.Interop.csproj
Build and Run:
# From Examples/Interop directory
.\build.ps1TypeScript Features Demonstrated:
- Classes with constructors and methods
- Instance and static members
- Property accessors
- Class inheritance with
extends - Method overriding
- Top-level functions
- Arrays and collections
C# Interop Patterns:
- Loading compiled TypeScript assemblies with
Assembly.LoadFrom() - Type discovery via
Assembly.GetType() - Instance creation with
Activator.CreateInstance() - Property access via
PropertyInfo(PascalCase naming) - Method invocation with
MethodInfo.Invoke() - Static member access with
BindingFlags.Static - Working with inheritance hierarchies
- Accessing top-level functions via
$Programclass
Type Mapping:
| TypeScript | .NET Runtime |
|---|---|
number |
double |
string |
string |
boolean |
bool |
T[] |
List<object> |
See Examples/Interop/README.md for detailed documentation.
What it does: A demonstration HTTP server with routing, static HTML pages, and dynamic JSON API endpoints. Showcases SharpTS's HTTP server capabilities.
Usage:
# Start server on default port 3000
sharpts Examples/web-server.ts
# Start server on custom port
sharpts Examples/web-server.ts 8080
# Show help
sharpts Examples/web-server.ts --helpDemonstrates:
httpmodule:createServer(), server events (on('listening'),on('error'))- Request properties:
method,url,headers,socket - Response methods:
writeHead(),end() urlmodule:parse()for URL parsingquerystringmodule:parse()for query string parsing- Content-Type headers (text/html, application/json)
- HTTP status codes (200, 404)
- Path parameter extraction from URLs
Key Features:
- Multiple route handlers with pattern matching
- Static HTML pages with inline CSS styling
- Dynamic JSON API endpoints
- Request logging to console
- XSS prevention via HTML escaping
- Personalized greetings with path parameters
- Echo endpoint showing request details
Routes:
| Route | Method | Response | Description |
|---|---|---|---|
/ |
GET | HTML | Home page with navigation links |
/about |
GET | HTML | About page with server info |
/api/time |
GET | JSON | Current server timestamp |
/api/echo |
GET | JSON | Echo request info (method, url, headers, query) |
/api/greet/:name |
GET | JSON | Personalized greeting with path parameter |
* |
ANY | HTML | 404 Not Found page |
This table shows which SharpTS/TypeScript features each example demonstrates:
| Feature | file-hasher | file-organizer | password-generator | system-info | url-toolkit | source-analyzer | interop | web-server |
|---|---|---|---|---|---|---|---|---|
| Classes | ✓ | ✓ | ||||||
| Interfaces | ✓ | |||||||
| Inheritance | ✓ | |||||||
| For-of loops | ✓ | ✓ | ✓ | ✓ | ✓ | |||
| While loops | ✓ | ✓ | ||||||
| Object literals | ✓ | ✓ | ✓ | |||||
| Arrays | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | |
| String manipulation | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ |
| Type annotations | ✓ | ✓ | ||||||
| Functions | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ |
| Modules (import) | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | |
| CLI arguments | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ||
| File I/O | ✓ | ✓ | ✓ | |||||
| Crypto | ✓ | ✓ | ||||||
| User input | ✓ | ✓ | ||||||
| Process info | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | |
| OS info | ✓ | |||||||
| Path manipulation | ✓ | ✓ | ✓ | ✓ | ||||
| URL parsing | ✓ | ✓ | ||||||
| HTTP server | ✓ | |||||||
| C# interop | ✓ |
SharpTS provides Node.js-compatible built-in modules:
File System (fs)
readFileSync()- Read file contentsreaddirSync()- List directory entriesstatSync()- Get file/directory statsexistsSync()- Check if path existsmkdirSync()- Create directoryrenameSync()- Move/rename files
Path (path)
join()- Combine path segmentsresolve()- Resolve absolute pathbasename()- Get filename from pathextname()- Get file extensionisAbsolute()- Check if path is absolute
Crypto (crypto)
createHash()- Create hash instancerandomBytes()- Generate random bytesrandomInt()- Generate random integer
OS (os)
platform(),arch(),type(),release()- OS informationhostname()- System hostnamecpus()- CPU informationtotalmem(),freemem()- Memory informationhomedir(),tmpdir()- Directory pathsuserInfo()- Current user information
Process (process)
argv- Command-line argumentsenv- Environment variablescwd()- Current working directorypid- Process IDversion- Node versionuptime()- Process uptimememoryUsage()- Process memory usageexit()- Exit with code
URL (url)
parse()- Parse URL stringresolve()- Resolve relative URLs
Query String (querystring)
parse()- Parse query stringstringify()- Build query stringescape()- URL encodeunescape()- URL decode
Readline (readline)
questionSync()- Synchronous user input
HTTP (http)
createServer(handler)- Create an HTTP server- Server methods:
listen(port, callback?),close(callback?) - Server events:
on('listening'),on('error'),on('request') - Server properties:
listening,address() - Request properties:
method,url,headers,socket,httpVersion - Response methods:
writeHead(status, headers?),write(data),end(data?),setHeader(name, value) - Response properties:
statusCode,statusMessage,headersSent
Interpreted mode (faster for development):
sharpts Examples/<example>.tsCompiled mode (better performance, standalone executable):
# Compile
sharpts --compile Examples/<example>.ts
# Run the compiled assembly
dotnet Examples/<example>.dllView help for examples: Most examples display usage information when run without arguments:
sharpts Examples/file-hasher.tsRecommended order for exploring examples:
- system-info.ts - Start here to see basic built-in modules
- file-hasher.ts - Learn file operations and crypto
- password-generator.ts - Explore user input and randomness
- file-organizer.ts - Practice file system manipulation
- url-toolkit.ts - Interactive CLI patterns
- web-server.ts - HTTP server with routing and APIs
- source-analyzer.ts - Complex application with interfaces
- Interop/ - Advanced: C# interoperability
When creating new examples:
- Add a comment header explaining usage and demonstrated features
- Include a
main()function for organization - Use
process.argv.slice(2)for command-line arguments - Provide helpful error messages
- Show usage information when run without required arguments
- Consider adding both interpreted and compiled usage examples
Example template:
// My Example - Brief description
// Usage: sharpts Examples/my-example.ts <args>
//
// Demonstrates: feature1, feature2, feature3
import module from 'module';
import process from 'process';
function main(): void {
const args = process.argv.slice(2);
if (args.length === 0) {
console.log('My Example - Description');
console.log('');
console.log('Usage: sharpts Examples/my-example.ts <args>');
return;
}
// Your code here
}
main();- SharpTS README (
../README.md) - Project overview and build instructions - CLAUDE.md (
../CLAUDE.md) - Detailed architecture and development guide - Test Suite (
../SharpTS.Tests/) - Comprehensive feature tests - Interop Documentation (
Interop/README.md) - C# interop details
Have an interesting example? Consider:
- Demonstrating a specific SharpTS feature
- Solving a practical problem
- Showing idiomatic TypeScript patterns
- Highlighting interop capabilities
Keep examples focused, well-documented, and easy to run.