如何在Node.js中终止上传至GCS的文件进程
I'm using the Google Cloud Storage Node.js SDK to upload files, and I need to terminate an ongoing upload process. Here's my current implementation:
const uploadFile = async ({ bucketName, filePath, destFileName }) => { const storage = new Storage(); await storage.bucket(bucketName).upload(filePath, { "destination": destFileName, }); };How can I implement a way to cancel this upload?
Hey there,
To cancel an ongoing GCS upload, you can leverage Node.js's AbortController (supported in Node.js 15+), which the @google-cloud/storage library fully supports. This lets you send an abort signal to the upload request at any time.
Here's how to modify your code to add cancellation functionality:
Step 1: Integrate AbortController into your upload function
Update your uploadFile function to accept an optional abort signal, so you can control cancellation from outside the function scope:
const uploadFile = async ({ bucketName, filePath, destFileName, abortSignal }) => { const storage = new Storage(); try { await storage.bucket(bucketName).upload(filePath, { destination: destFileName, // Pass the abort signal to the upload configuration signal: abortSignal }); } catch (err) { // Handle the abort error specifically if (err.name === 'AbortError') { console.log('Upload was cancelled successfully'); return; } // Re-throw other errors for upstream handling throw err; } };
Step 2: Trigger cancellation when needed
Create an AbortController instance, pass its signal to the upload, and call controller.abort() whenever you want to stop the in-progress upload (e.g., user action, timeout):
// Initialize the abort controller const uploadController = new AbortController(); const { signal } = uploadController; // Start the upload in the background uploadFile({ bucketName: 'your-target-bucket', filePath: './local-file-to-upload.txt', destFileName: 'gcs-destination-file.txt', abortSignal: signal }).catch(err => console.error('Upload failed:', err)); // Example: Cancel the upload after 5 seconds setTimeout(() => { uploadController.abort(); }, 5000);
Key Details:
- The
signalparameter is natively supported by the GCS SDK, so it properly terminates the underlying HTTP request to Google's servers, not just stops local execution. - When you call
abort(), the upload promise will reject with anAbortError—you can catch this to handle cancellation gracefully without treating it as a regular failure. - Ensure you're using a version of
@google-cloud/storagethat supports thesignaloption (v5.10.0+ is safe, but using the latest stable version is recommended).
That's all you need! This approach gives you full control to cancel in-progress uploads whenever required.
内容的提问来源于stack exchange,提问作者Hafiz Muhammad Bilal

