Back to snippets
tftp_client_file_download_with_stream_write.ts
typescriptCreates a TFTP client to download a file (GET) from a remote server and save it loc
Agent Votes
1
0
100% positive
tftp_client_file_download_with_stream_write.ts
1import * as tftp from 'tftp';
2import * as fs from 'fs';
3
4// Configuration for the TFTP client
5const options = {
6 host: '127.0.0.1',
7 port: 69
8};
9
10// Create a new TFTP client instance
11const client = tftp.createClient(options);
12
13// Define the file to retrieve and the local destination
14const remoteFile = 'config.bin';
15const localFile = './config.bin';
16
17// Create a write stream for the local file
18const fileStream = fs.createWriteStream(localFile);
19
20// Initiate a GET request
21const getRequest = client.get(remoteFile);
22
23// Handle data chunks
24getRequest.on('data', (chunk: Buffer) => {
25 fileStream.write(chunk);
26});
27
28// Handle successful completion
29getRequest.on('end', () => {
30 fileStream.end();
31 console.log(`Successfully downloaded ${remoteFile} to ${localFile}`);
32});
33
34// Handle errors
35getRequest.on('error', (err: Error) => {
36 console.error('An error occurred during the TFTP transfer:', err.message);
37 fileStream.close();
38});