### Install @awo00/smb2 Source: https://github.com/awo00/smb2/blob/master/README.md Use npm to install the package in your project. ```sh $ npm i @awo00/smb2 ``` -------------------------------- ### Install AWO00 SMB2 Source: https://context7.com/awo00/smb2/llms.txt Use npm to install the library in your Node.js project. ```bash npm i @awo00/smb2 ``` -------------------------------- ### Create Directories with TypeScript Source: https://context7.com/awo00/smb2/llms.txt Use createDirectory to add new folders. Nested directories must be created sequentially starting from the parent. ```typescript import smb2 from "@awo00/smb2"; const client = new smb2.Client("fileserver.local"); const session = await client.authenticate({ domain: "CORP", username: "user", password: "password" }); const tree = await session.connectTree("Documents"); // Create a single directory await tree.createDirectory("/NewFolder"); // Create nested directories (parent must exist) await tree.createDirectory("/Projects"); await tree.createDirectory("/Projects/2024"); await tree.createDirectory("/Projects/2024/Q1"); await client.close(); ``` -------------------------------- ### Connect and Read Directory with SMB2 Source: https://github.com/awo00/smb2/blob/master/README.md Initialize a client, authenticate a session, connect to a share, and list directory contents. ```ts import smb2 from "@awo00/smb2"; const client = new smb2.Client(host); const session = await client.authenticate({ domain, username, password }); const tree = await session.connectTree(share); const entries = await tree.readDirectory("/"); console.log(entries); ``` -------------------------------- ### Initialize and Connect SMB Client Source: https://context7.com/awo00/smb2/llms.txt Establish a TCP connection to an SMB server using the Client class. Options allow for custom port and timeout configurations. ```typescript import smb2 from "@awo00/smb2"; // Basic client initialization const client = new smb2.Client("192.168.1.100"); // Client with custom options const clientWithOptions = new smb2.Client("192.168.1.100", { port: 445, // Default SMB port connectTimeout: 5000, // Connection timeout in ms (default: 5000) requestTimeout: 5000 // Request timeout in ms (default: 5000) }); // Manual connection (optional - authenticate() calls this automatically) await client.connect(); // Check connection status console.log(client.connected); // true // Close client and all sessions gracefully await client.close(); ``` -------------------------------- ### Connect to SMB Share Source: https://context7.com/awo00/smb2/llms.txt Use the Tree class to connect to a specific share on the server for file operations. ```typescript import smb2 from "@awo00/smb2"; const client = new smb2.Client("192.168.1.100"); const session = await client.authenticate({ domain: "WORKGROUP", username: "admin", password: "secretpass" }); // Connect to a share (e.g., \\server\sharename) const tree = await session.connectTree("SharedFolder"); // Tree events tree.on("connect", (t) => { console.log("Connected to share"); }); tree.on("disconnect", (t) => { console.log("Disconnected from share"); }); // Disconnect from the share await tree.disconnect(); // Close the entire client (disconnects all trees and sessions) await client.close(); ``` -------------------------------- ### Create Files with TypeScript Source: https://context7.com/awo00/smb2/llms.txt Use createFile to generate files with optional string or Buffer content. ```typescript import smb2 from "@awo00/smb2"; const client = new smb2.Client("fileserver.local"); const session = await client.authenticate({ domain: "CORP", username: "user", password: "password" }); const tree = await session.connectTree("Documents"); // Create an empty file await tree.createFile("/empty.txt"); // Create a file with string content await tree.createFile("/hello.txt", "Hello, World!"); // Create a file with Buffer content const buffer = Buffer.from("Binary data here", "utf8"); await tree.createFile("/data.bin", buffer); // Create a JSON configuration file const config = { server: "localhost", port: 8080 }; await tree.createFile("/config.json", JSON.stringify(config, null, 2)); await client.close(); ``` -------------------------------- ### Perform SMB2 operations with TypeScript Source: https://context7.com/awo00/smb2/llms.txt Demonstrates the full lifecycle of an SMB2 connection, including authentication, file system operations, and directory watching. Ensure the client is closed in a finally block or error handler to prevent connection leaks. ```typescript import smb2 from "@awo00/smb2"; async function main() { const client = new smb2.Client("192.168.1.100", { connectTimeout: 10000, requestTimeout: 30000 }); try { // Authenticate const session = await client.authenticate({ domain: "WORKGROUP", username: "admin", password: "password123" }); console.log("Authenticated successfully"); // Connect to share const tree = await session.connectTree("SharedDocs"); console.log("Connected to share"); // List root directory const entries = await tree.readDirectory("/"); console.log("Root directory contents:"); entries.forEach(entry => { const size = entry.type === "File" ? ` (${entry.fileSize} bytes)` : ""; console.log(` [${entry.type}] ${entry.filename}${size}`); }); // Create a working directory const workDir = "/automation-test"; if (!await tree.exists(workDir)) { await tree.createDirectory(workDir); console.log(`Created directory: ${workDir}`); } // Create a file with content const testFile = `${workDir}/test.txt`; await tree.createFile(testFile, "Hello from SMB2 client!"); console.log(`Created file: ${testFile}`); // Read it back const content = await tree.readFile(testFile); console.log(`File content: ${content.toString()}`); // Rename the file const renamedFile = `${workDir}/renamed.txt`; await tree.renameFile(testFile, renamedFile); console.log(`Renamed to: ${renamedFile}`); // Set up a file watcher const unwatch = await tree.watchDirectory(workDir, (response) => { console.log("Change detected:", response.data); }); // Clean up - remove file and directory await tree.removeFile(renamedFile); console.log("Removed test file"); await tree.removeDirectory(workDir); console.log("Removed test directory"); // Stop watching await unwatch(); // Close connection gracefully await client.close(); console.log("Connection closed"); } catch (error) { console.error("Error:", error); await client.close(); } } main(); ``` -------------------------------- ### Authenticate SMB Session Source: https://context7.com/awo00/smb2/llms.txt Perform NTLM authentication using domain credentials to establish a session. ```typescript import smb2 from "@awo00/smb2"; const client = new smb2.Client("192.168.1.100"); // Authenticate with domain credentials const session = await client.authenticate({ domain: "WORKGROUP", // Windows domain or workgroup name username: "admin", // Username password: "secretpass" // Password }); // Check authentication status console.log(session.authenticated); // true // Session events session.on("authenticate", (sess) => { console.log("Session authenticated"); }); session.on("logoff", (sess) => { console.log("Session logged off"); }); // Manual logoff (called automatically by client.close()) await session.logoff(); ``` -------------------------------- ### Read SMB Directory Contents Source: https://context7.com/awo00/smb2/llms.txt Retrieve metadata for files and directories within a specified path using the readDirectory method. ```typescript import smb2 from "@awo00/smb2"; const client = new smb2.Client("fileserver.local"); const session = await client.authenticate({ domain: "CORP", username: "user", password: "password" }); const tree = await session.connectTree("Documents"); // Read root directory const rootEntries = await tree.readDirectory("/"); // Read a subdirectory const subEntries = await tree.readDirectory("/Reports/2024"); // Process directory entries for (const entry of rootEntries) { console.log({ filename: entry.filename, // "report.docx" type: entry.type, // "File" or "Directory" fileSize: entry.fileSize, // BigInt file size creationTime: entry.creationTime, // Date object lastWriteTime: entry.lastWriteTime, lastAccessTime: entry.lastAccessTime, changeTime: entry.changeTime, fileAttributes: entry.fileAttributes // ["Archive", "Normal"] }); } await client.close(); ``` -------------------------------- ### Monitor File System Changes Source: https://context7.com/awo00/smb2/llms.txt Watch shares or directories for file system events. Supports recursive and non-recursive monitoring. ```typescript import smb2 from "@awo00/smb2"; const client = new smb2.Client("fileserver.local"); const session = await client.authenticate({ domain: "CORP", username: "user", password: "password" }); const tree = await session.connectTree("Documents"); // Watch entire share for changes (recursive) const unwatchShare = await tree.watch((response) => { console.log("Share changed:", response.data); }); // Watch a specific directory const unwatchDir = await tree.watchDirectory("/Projects", (response) => { console.log("Projects directory changed:", response.data); // response.data contains change entries with: // - action: "Added", "Removed", "Modified", "RenamedOldName", "RenamedNewName" // - filename: affected file/directory name }, true); // true = recursive watching // Watch non-recursively (only immediate children) const unwatchNonRecursive = await tree.watchDirectory("/Inbox", (response) => { console.log("Inbox changed:", response.data); }, false); // Stop watching after some time setTimeout(async () => { await unwatchShare(); await unwatchDir(); await unwatchNonRecursive(); console.log("Stopped watching"); await client.close(); }, 60000); ``` -------------------------------- ### Rename and Move Files with SMB2 Source: https://context7.com/awo00/smb2/llms.txt Renames or moves files on the remote share. Supports dynamic naming using timestamps. ```typescript import smb2 from "@awo00/smb2"; const client = new smb2.Client("fileserver.local"); const session = await client.authenticate({ domain: "CORP", username: "user", password: "password" }); const tree = await session.connectTree("Documents"); // Rename a file await tree.renameFile("/draft.txt", "/final.txt"); // Move a file to another directory await tree.renameFile("/inbox/document.pdf", "/archive/document.pdf"); // Rename with timestamp const timestamp = new Date().toISOString().replace(/[:.]/g, "-"); await tree.renameFile("/report.csv", `/archive/report-${timestamp}.csv`); await client.close(); ``` -------------------------------- ### Remove Files with SMB2 Source: https://context7.com/awo00/smb2/llms.txt Deletes files from a remote share. Use a loop to handle multiple file deletions with error catching. ```typescript import smb2 from "@awo00/smb2"; const client = new smb2.Client("fileserver.local"); const session = await client.authenticate({ domain: "CORP", username: "user", password: "password" }); const tree = await session.connectTree("Documents"); // Remove a single file await tree.removeFile("/obsolete.txt"); // Remove multiple files const filesToDelete = ["/temp1.txt", "/temp2.txt", "/temp3.txt"]; for (const file of filesToDelete) { try { await tree.removeFile(file); console.log(`Deleted: ${file}`); } catch (err) { console.error(`Failed to delete ${file}:`, err); } } await client.close(); ``` -------------------------------- ### Read Files with TypeScript Source: https://context7.com/awo00/smb2/llms.txt Use readFile to retrieve file contents as a Buffer, which can then be converted to strings or parsed as JSON. ```typescript import smb2 from "@awo00/smb2"; const client = new smb2.Client("fileserver.local"); const session = await client.authenticate({ domain: "CORP", username: "user", password: "password" }); const tree = await session.connectTree("Documents"); // Read file as Buffer const buffer = await tree.readFile("/report.txt"); // Convert to string const content = buffer.toString("utf8"); console.log(content); // Read and parse JSON file const configBuffer = await tree.readFile("/config.json"); const config = JSON.parse(configBuffer.toString("utf8")); console.log(config); // Read binary file const imageBuffer = await tree.readFile("/images/logo.png"); console.log(`Image size: ${imageBuffer.length} bytes`); await client.close(); ``` -------------------------------- ### Check Existence with TypeScript Source: https://context7.com/awo00/smb2/llms.txt Use exists to verify if a file or directory is present before performing operations. ```typescript import smb2 from "@awo00/smb2"; const client = new smb2.Client("fileserver.local"); const session = await client.authenticate({ domain: "CORP", username: "user", password: "password" }); const tree = await session.connectTree("Documents"); // Check if a file exists const fileExists = await tree.exists("/config.json"); console.log(fileExists); // true or false // Check if a directory exists const dirExists = await tree.exists("/Backups"); console.log(dirExists); // true or false // Conditional file creation if (!await tree.exists("/logs")) { await tree.createDirectory("/logs"); } if (!await tree.exists("/logs/app.log")) { await tree.createFile("/logs/app.log", "Log started\n"); } await client.close(); ``` -------------------------------- ### Rename or Move Directories with TypeScript Source: https://context7.com/awo00/smb2/llms.txt Use renameDirectory to change a directory's name or move it to a different path. ```typescript import smb2 from "@awo00/smb2"; const client = new smb2.Client("fileserver.local"); const session = await client.authenticate({ domain: "CORP", username: "user", password: "password" }); const tree = await session.connectTree("Documents"); // Rename a directory await tree.renameDirectory("/OldName", "/NewName"); // Move a directory (rename with different path) await tree.renameDirectory("/Temp/WorkInProgress", "/Archive/Completed"); await client.close(); ``` -------------------------------- ### Write Files Using Streams Source: https://context7.com/awo00/smb2/llms.txt Efficiently write large files or data chunks using write streams or the pipeline utility. ```typescript import smb2 from "@awo00/smb2"; import { createReadStream } from "fs"; import { pipeline } from "stream/promises"; const client = new smb2.Client("fileserver.local"); const session = await client.authenticate({ domain: "CORP", username: "user", password: "password" }); const tree = await session.connectTree("Documents"); // Create a write stream const writeStream = await tree.createFileWriteStream("/large-file.bin"); // Write data in chunks writeStream.write(Buffer.from("First chunk of data")); writeStream.write(Buffer.from("Second chunk of data")); writeStream.end(); // Wait for stream to close writeStream.on("close", () => { console.log(`Bytes written: ${writeStream.bytesWritten}`); }); // Or use pipeline to copy from local file const localReadStream = createReadStream("/local/path/bigfile.zip"); const remoteWriteStream = await tree.createFileWriteStream("/backup/bigfile.zip"); await pipeline(localReadStream, remoteWriteStream); console.log("File uploaded successfully"); await client.close(); ``` -------------------------------- ### Read Files Using Streams Source: https://context7.com/awo00/smb2/llms.txt Efficiently read large files using read streams or the pipeline utility for downloading. ```typescript import smb2 from "@awo00/smb2"; import { createWriteStream } from "fs"; import { pipeline } from "stream/promises"; const client = new smb2.Client("fileserver.local"); const session = await client.authenticate({ domain: "CORP", username: "user", password: "password" }); const tree = await session.connectTree("Documents"); // Create a read stream const readStream = await tree.createFileReadStream("/large-file.bin"); // Process data as it streams let totalBytes = 0; for await (const chunk of readStream) { totalBytes += chunk.length; // Process each chunk console.log(`Received chunk: ${chunk.length} bytes`); } console.log(`Total bytes read: ${totalBytes}`); // Or use pipeline to download to local file const remoteReadStream = await tree.createFileReadStream("/backup/database.sql"); const localWriteStream = createWriteStream("/local/path/database.sql"); await pipeline(remoteReadStream, localWriteStream); console.log("File downloaded successfully"); await client.close(); ``` -------------------------------- ### Remove Directories with TypeScript Source: https://context7.com/awo00/smb2/llms.txt Use removeDirectory to delete folders. The directory must be empty, and nested structures require deleting children first. ```typescript import smb2 from "@awo00/smb2"; const client = new smb2.Client("fileserver.local"); const session = await client.authenticate({ domain: "CORP", username: "user", password: "password" }); const tree = await session.connectTree("Documents"); // Remove an empty directory await tree.removeDirectory("/OldFolder"); // Remove nested directories (children first) await tree.removeDirectory("/Projects/2024/Q1"); await tree.removeDirectory("/Projects/2024"); await tree.removeDirectory("/Projects"); await client.close(); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.