Node.js如何等待响应返回?copy_deliverable_script_tomaster代码问题
Fixing the
copy_deliverable_script_tomaster Callback & Error Handling Issues First, let's break down the critical issues in your original code:
- Callback typo: The code cuts off at
callba...instead of properly invoking thecallbackfunction - Missing error propagation: When an error occurs, it only logs to the console but doesn't notify the caller via the callback—this will leave your HTTP request hanging, since
res.end("added")will never run - Unsafe path concatenation: String-based path joins can lead to unexpected issues like missing slashes
- Unchecked synchronous file read: Reading the private key with
fs.readFileSyncwithout error handling can crash the app if the file is missing or unreadable
Here's the revised, robust version of your code with fixes and best practices:
const fs = require('fs'); const path = require('path'); // Add path module for safe cross-platform path joining // Updated function with proper error handling and callback flow function copy_deliverable_script_tomaster(software_name, callback) { let privateKey; try { // Wrap sync read in try/catch to handle missing key file gracefully privateKey = fs.readFileSync('./foreman_keypairs/coe-central.pem', 'utf8'); } catch (readErr) { console.error('Failed to read private key:', readErr); return callback(readErr); // Pass error to caller immediately } // Use path.join to avoid invalid path strings const sourcePath = path.join('./Temporary_software_files', 'folder'); const targetPath = path.join('/home/centos/Software_with_files', software_name); client.scp(sourcePath, { host: 'ip', // Replace with your actual master server IP username: 'centos', privateKey: privateKey, path: targetPath }, function(err, response) { if (err) { console.error('SCP copy failed:', err); return callback(err); // Propagate error to the callback } console.log("after copy in master"); callback(null, response); // Pass success response to callback }); } // Usage with proper error handling in your route handler copy_deliverable_script_tomaster(args.Software_name.value, function(err, state) { if (err) { // Handle error properly - send an error response instead of success console.error('Error during copy operation:', err); return res.status(500).end('Copy failed'); } res.end("added"); });
Key Improvements Explained:
- Reliable callback flow: Both success and error cases now call the callback, ensuring your HTTP response is always sent (no hanging requests)
- Error propagation: Errors from key reading and SCP operations are passed to the caller, so you can handle them in your route logic instead of silently failing
- Safe path handling:
path.joinensures cross-platform compatibility and avoids invalid path strings caused by manual string concatenation - Crash prevention: Wrapping
fs.readFileSyncin a try/catch stops the app from crashing if the private key file is missing or unreadable - Predictable API behavior: The usage example now checks for errors and sends a 500 status code on failure, making your API's behavior clear to clients
内容的提问来源于stack exchange,提问作者Pooja
相关产品推荐
相关产品推荐

