CSV 檔案轉換為純文字 TXT 格式是常見需求,尤其在需要輕量級資料提取以進行記錄或後續處理時。Aspose.PDF Cloud SDK for Node.JS 提供功能強大的函式庫,可在雲端處理檔案儲存與格式轉換。在本指南中,您將看到一步一步的實作範例,說明如何上傳 CSV、將其轉換為 TXT,並使用 async/await 將結果儲存至本機。範例同時示範了暫存檔案的清除以及基本的錯誤處理。

如何在 Node.JS 中將 CSV 轉換為 TXT - 步驟說明

  1. 安裝庫並匯入所需模組:將套件加入您的專案並引用所需的類別。
const fs = require('fs');
const path = require('path');
const { PdfApi } = require('asposepdfcloud');
  1. 使用您的憑證初始化 PdfApi: 使用您的 client ID 和 secret 建立 PdfApi 的實例。
const clientId = 'YOUR_CLIENT_ID';
const clientSecret = 'YOUR_CLIENT_SECRET';
const pdfApi = new PdfApi(clientId, clientSecret);
  1. 上傳 CSV 檔案至 Aspose Cloud storage:使用 uploadFile 將本機 CSV 傳輸至雲端。
const localCsvPath = path.resolve(__dirname, 'input.csv');
const remoteCsvPath = 'input.csv';
await pdfApi.uploadFile(remoteCsvPath, fs.createReadStream(localCsvPath));
  1. 將上傳的 CSV 轉換為 TXT:呼叫 getDocument 並將目標格式設為 'txt'
const convertResponse = await pdfApi.getDocument(remoteCsvPath, null, 'txt');
  1. 將 TXT 串流儲存至本機並清理:將回應主體導入檔案,並可選擇刪除遠端 CSV。
const localTxtPath = path.resolve(__dirname, 'output.txt');
const writeStream = fs.createWriteStream(localTxtPath);
await new Promise((resolve, reject) => {
    convertResponse.body.pipe(writeStream);
    convertResponse.body.on('error', reject);
    writeStream.on('finish', resolve);
    writeStream.on('error', reject);
});
await pdfApi.deleteFile(remoteCsvPath); // optional cleanup

如需了解 PdfApi 類別的更多詳細資訊,請參閱 API 參考

完整程式碼範例:使用 Aspose.PDF 進行 CSV 到 TXT 轉換

以下程式碼示範了從上傳 CSV 檔案到取得已轉換的 TXT 檔案的完整工作流程。

const fs = require('fs');
const path = require('path');
const { PdfApi } = require('asposepdfcloud');

// Replace with your actual Aspose PDF Cloud credentials
const clientId = 'YOUR_CLIENT_ID';
const clientSecret = 'YOUR_CLIENT_SECRET';

// Initialize the PdfApi instance
const pdfApi = new PdfApi(clientId, clientSecret);

// Paths (adjust as needed)
const localCsvPath = path.resolve(__dirname, 'input.csv');
const remoteCsvPath = 'input.csv'; // Path in Aspose Cloud storage
const localTxtPath = path.resolve(__dirname, 'output.txt');

async function convertCsvToTxt() {
    try {
        // 1. Upload the CSV file to Aspose Cloud storage
        const uploadResponse = await pdfApi.uploadFile(remoteCsvPath, fs.createReadStream(localCsvPath));
        if (uploadResponse.status !== 'OK') {
            throw new Error(`Upload failed: ${JSON.stringify(uploadResponse)}`);
        }
        console.log('CSV file uploaded successfully.');

// 2. Convert the uploaded CSV to TXT format
        const convertResponse = await pdfApi.getDocument(remoteCsvPath, null, 'txt');
        if (!convertResponse.body) {
            throw new Error('Conversion response does not contain a body stream.');
        }

// 3. Save the converted TXT stream to a local file
        const writeStream = fs.createWriteStream(localTxtPath);
        await new Promise((resolve, reject) => {
            convertResponse.body.pipe(writeStream);
            convertResponse.body.on('error', reject);
            writeStream.on('finish', resolve);
            writeStream.on('error', reject);
        });
        console.log(`Conversion completed. TXT saved to ${localTxtPath}`);

// 4. (Optional) Clean up: delete the CSV file from cloud storage
        const deleteResponse = await pdfApi.deleteFile(remoteCsvPath);
        if (deleteResponse.status !== 'OK') {
            console.warn(`Failed to delete remote CSV: ${JSON.stringify(deleteResponse)}`);
        } else {
            console.log('Remote CSV file deleted.');
        }
    } catch (error) {
        console.error('An error occurred:', error.message);
    }
}

// Execute the conversion
convertCsvToTxt();

注意: 此程式碼範例示範了核心功能。 在將其用於您的專案之前,請確保更新所有檔案路徑和設定值以符合實際環境,驗證所有必要的相依項目已正確安裝,並在開發環境中徹底測試。 若遇到任何問題,請參閱官方文件或聯繫支援團隊以獲得協助。

使用 cURL 將 CSV 檔案轉換為 TXT

您可以直接使用 REST API 完成相同的轉換。以下步驟說明如何取得存取權杖、上傳 CSV、發出轉換請求,並下載產生的 TXT 檔案。

  1. 取得存取權杖
curl -X POST "https://api.aspose.cloud/connect/token" \
     -H "Content-Type: application/x-www-form-urlencoded" \
     -d "grant_type=client_credentials&client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET"
  1. 上傳 CSV 檔案
curl -X PUT "https://api.aspose.cloud/v3.0/pdf/storage/file/input.csv" \
     -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
     -H "Content-Type: text/csv" \
     --data-binary @input.csv
  1. 將上傳的 CSV 轉換為 TXT
curl -X GET "https://api.aspose.cloud/v3.0/pdf/input.csv?format=txt" \
     -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
     -o output.txt
  1. 刪除遠端 CSV 檔案(可選)
curl -X DELETE "https://api.aspose.cloud/v3.0/pdf/storage/file/input.csv" \
     -H "Authorization: Bearer YOUR_ACCESS_TOKEN"

如需完整的參數清單,請參閱官方 API 文件

安裝與設定 Aspose.PDF Cloud SDK for Node.JS

使用 npm 將庫添加到您的專案,並確保您擁有有效的 Aspose Cloud 帳戶。

npm install asposepdfcloud

您也可以直接從發行頁面下載套件。此庫需要 Node.js 12 或更高版本,並且需要有效的 Aspose Cloud 訂閱。

Aspose.PDF Cloud SDK 用於 CSV 轉 TXT 任務的主要功能

  • 雲端儲存整合 - 檔案儲存在 Aspose Cloud 中,消除本機磁碟的限制。
  • 即時轉換 - getDocument 方法回傳串流,允許即時處理而無需中間檔案。
  • 支援 Async/await - 所有操作皆回傳 Promise,自然契合現代 Node.JS 程式碼基礎。
  • 串流 I/O - 上傳與下載皆以串流方式進行,降低大型 CSV 檔案的記憶體使用。
  • 完整格式支援 - 除了 TXT,相同的 API 還能轉換為 PDFDOCXHTML,等等。

微調 CSV 轉 TXT 的轉換選項

雖然基本的轉換只需要目標格式,但您可以使用其他參數(例如儲存名稱或資料夾位置)自訂請求。getDocument 方法接受 folder 參數(在範例中設為 null)以及在使用自訂儲存時的 storage 參數。

指定儲存名稱的範例(程式碼片段已在主流程中使用):

const convertResponse = await pdfApi.getDocument(remoteCsvPath, null, 'txt');

如需完整的可選參數列表,請參閱 API 參考

結論

在 Node.JS 中將 CSV 轉換為 TXT 變得簡單,使用 Aspose.PDF Cloud SDK for Node.JS。此函式庫處理驗證、雲端儲存和串流轉換,讓您專注於業務邏輯。請務必在產品頁面上檢視定價細節,並從 臨時授權頁面 取得臨時授權以進行評估,然後再投入生產環境。本指南中的程式碼和 cURL 範例,可讓您快速且可靠地將 CSV 轉換為 TXT,整合至任何 Node.JS 應用程式中。

常見問題

如何在 Node.JS 中使用 Aspose.PDF 將 CSV 轉換為 TXT?
使用該庫上傳 CSV,調用 getDocument 並指定 'txt' 格式,然後將回應流式傳輸到本機文件。上面的完整代碼示例展示了每個步驟。

此函式庫使用哪種驗證方法?
Provide your client ID and client secret; the library obtains an OAuth token automatically and includes it in each request.

轉換能有效處理大型檔案嗎?
是的。上傳和下載皆以串流方式進行,因此即使是大型 CSV 檔案也能在不將整個內容載入記憶體的情況下處理。

我可以從哪裡取得測試用的臨時授權?
臨時授權可在臨時授權頁面取得。

閱讀更多