Comparing Word files programmatically is a frequent requirement for backend services that need to detect changes, generate revision reports, or enforce document policies. GroupDocs.Comparison Cloud SDK for Node.js provides a powerful API that simplifies this task for Node.js applications. In this guide you will learn how to set up the SDK, run a complete comparison of two DOCX files, use equivalent cURL commands, understand each part of the implementation, and follow best‑practice recommendations to keep your solution reliable and secure.
Complete Code Example: Compare Word Documents in Node.JS
The following example demonstrates a full end‑to‑end workflow for comparing two Word documents using the GroupDocs.Comparison Cloud SDK for Node.js.
const GroupDocsComparisonCloud = require("@groupdocs/comparison-cloud");
const fs = require("fs");
const path = require("path");
// ==== Authentication =========================================================
const clientId = "YOUR_CLIENT_ID";
const clientSecret = "YOUR_CLIENT_SECRET";
const config = new GroupDocsComparisonCloud.Configuration(clientId, clientSecret);
const compareApi = new GroupDocsComparisonCloud.CompareApi(config);
const storageApi = new GroupDocsComparisonCloud.StorageApi(config);
// ==== File definitions =======================================================
const sourceFileName = "document1.docx";
const targetFileName = "document2.docx";
const resultFileName = "comparison_result.docx";
const sourceFilePath = path.resolve(__dirname, sourceFileName);
const targetFilePath = path.resolve(__dirname, targetFileName);
// ==== Main async function ====================================================
(async () => {
try {
// ---- Upload source document -----------------------------------------
const sourceData = fs.readFileSync(sourceFilePath);
const uploadSourceReq = new GroupDocsComparisonCloud.UploadFileRequest({
path: sourceFileName,
file: sourceData
});
await storageApi.uploadFile(uploadSourceReq);
// ---- Upload target document -----------------------------------------
const targetData = fs.readFileSync(targetFilePath);
const uploadTargetReq = new GroupDocsComparisonCloud.UploadFileRequest({
path: targetFileName,
file: targetData
});
await storageApi.uploadFile(uploadTargetReq);
// ---- Prepare comparison options --------------------------------------
const compareOptions = new GroupDocsComparisonCloud.CompareOptions({
sourceFile: new GroupDocsComparisonCloud.FileInfo({ filePath: sourceFileName }),
targetFiles: [new GroupDocsComparisonCloud.FileInfo({ filePath: targetFileName })],
outputPath: resultFileName,
// optional: you can set settings like generateSummaryPage, showDeletedContent, etc.
});
const compareRequest = new GroupDocsComparisonCloud.CompareDocumentRequest({
compareOptions: compareOptions
});
// ---- Execute comparison -----------------------------------------------
const compareResult = await compareApi.compareDocument(compareRequest);
console.log("Comparison completed. Result stored at:", compareResult.path);
// ---- (Optional) Clean up uploaded files --------------------------------
await storageApi.deleteFile(new GroupDocsComparisonCloud.DeleteFileRequest({ path: sourceFileName }));
await storageApi.deleteFile(new GroupDocsComparisonCloud.DeleteFileRequest({ path: targetFileName }));
// Note: result file remains in storage; you can download it if needed.
} catch (error) {
console.error("Error during comparison:", error);
}
})();
Note: This code example demonstrates the core functionality. Before using it in your project, make sure to update any file paths and configuration values to match your actual environment, verify that all required dependencies are properly installed, and test thoroughly in your development environment. If you encounter any issues, please refer to the official documentation or reach out to the support team for assistance.
Perform Document Comparison with cURL and the REST API
If you prefer a language‑agnostic approach, you can achieve the same result with plain HTTP requests. Below are the essential cURL commands.
- Authenticate and obtain an access token
ReplaceYOUR_CLIENT_IDandYOUR_CLIENT_SECRETwith your credentials.
curl -X POST "https://api.groupdocs.cloud/v2.0/oauth2/token" \
-H "Content-Type: application/x-www-form-urlencoded" \
-d "grant_type=client_credentials&client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET"
- Upload the source DOCX file
curl -X PUT "https://api.groupdocs.cloud/v2.0/storage/file/document1.docx" \
-H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
-H "Content-Type: application/octet-stream" \
--data-binary "@path/to/document1.docx"
- Upload the target DOCX file
curl -X PUT "https://api.groupdocs.cloud/v2.0/storage/file/document2.docx" \
-H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
-H "Content-Type: application/octet-stream" \
--data-binary "@path/to/document2.docx"
- Execute the comparison operation
curl -X POST "https://api.groupdocs.cloud/v2.0/comparison/compare" \
-H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"sourceFile": { "filePath": "document1.docx" },
"targetFiles": [{ "filePath": "document2.docx" }],
"outputPath": "comparison_result.docx"
}'
- Download the resulting comparison file
curl -X GET "https://api.groupdocs.cloud/v2.0/storage/file/comparison_result.docx" \
-H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
-o comparison_result.docx
For more details on request payloads and response formats, see the official API documentation.
Understanding the Compare Word Documents in Node.JS Code
Below is a step‑by‑step breakdown of the complete example:
Import SDK and Node.js modules
const GroupDocsComparisonCloud = require("@groupdocs/comparison-cloud"); const fs = require("fs"); const path = require("path");The
GroupDocsComparisonCloudnamespace gives access to all API classes.Create configuration with client credentials
const config = new GroupDocsComparisonCloud.Configuration(clientId, clientSecret);This object authenticates every subsequent API call.
Instantiate CompareApi and StorageApi
const compareApi = new GroupDocsComparisonCloud.CompareApi(config); const storageApi = new GroupDocsComparisonCloud.StorageApi(config);CompareApihandles comparison, whileStorageApimanages file uploads and deletions. See the API reference for method details.Upload source and target DOCX files
const uploadSourceReq = new GroupDocsComparisonCloud.UploadFileRequest({ path: sourceFileName, file: sourceData }); await storageApi.uploadFile(uploadSourceReq);The same pattern is repeated for the target file.
Configure CompareOptions and run the comparison
const compareOptions = new GroupDocsComparisonCloud.CompareOptions({ sourceFile: new GroupDocsComparisonCloud.FileInfo({ filePath: sourceFileName }), targetFiles: [new GroupDocsComparisonCloud.FileInfo({ filePath: targetFileName })], outputPath: resultFileName, }); const compareRequest = new GroupDocsComparisonCloud.CompareDocumentRequest({ compareOptions: compareOptions }); const compareResult = await compareApi.compareDocument(compareRequest);CompareOptionslets you fine‑tune the operation (e.g., generate a summary page). The result object contains the path to the generated comparison document.Clean up temporary files (optional)
await storageApi.deleteFile(new GroupDocsComparisonCloud.DeleteFileRequest({ path: sourceFileName })); await storageApi.deleteFile(new GroupDocsComparisonCloud.DeleteFileRequest({ path: targetFileName }));Removing the uploaded originals keeps storage tidy.
Prerequisites and Setup for GroupDocs.Comparison
- Node.js version - Ensure you are running Node 14 or newer.
- Obtain client credentials - Register at the GroupDocs Cloud portal to get
clientIdandclientSecret. - Install the SDK
npm install groupdocs-comparison-cloud
- (Optional) Download the sample project - You can clone the repository from the GitHub page.
- Configure your environment - Set the credentials as environment variables or replace the placeholders in the code.
For a full list of downloadable binaries, see the download page.
Best Practices for Efficient Word Document Comparison
- Validate input files - Check file size and format before uploading to avoid unnecessary API calls.
- Reuse storage sessions - Upload files once and reuse their paths for multiple comparisons to reduce latency.
- Enable summary page only when needed - Generating a summary page adds processing time; disable it for simple diff checks.
- Handle large documents asynchronously - For DOCX files larger than 10 MB, consider polling the job status instead of waiting synchronously.
- Secure credentials - Store
clientIdandclientSecretin environment variables or a secret manager; never hard‑code them.
Conclusion
Comparing Word documents in Node.JS becomes straightforward with the GroupDocs.Comparison Cloud SDK for Node.js. By following the installation steps, using the provided code example, and optionally leveraging the REST API with cURL, you can integrate robust document comparison into any backend service. Remember to secure your credentials, clean up temporary files, and tune comparison options for performance. For production deployments you will need a licensed version; pricing details are available on the product page, and you can obtain a temporary license for evaluation from the temporary license page. Start experimenting today and bring reliable document diff capabilities to your Node.js applications.
FAQs
How do I compare Word documents in Node.JS without writing code?
You can use the same operation via REST calls. The cURL examples in this article show the exact sequence: authenticate, upload files, call the compare endpoint, and download the result.What file formats are supported for comparison?
The SDK supports DOCX, DOC, ODT, RTF, and TXT among others. All format names are case‑insensitive, but they are documented in uppercase (e.g., DOCX) in the API reference.Can I compare more than two documents at once?
Yes. ThetargetFilesarray inCompareOptionscan contain multipleFileInfoobjects, allowing you to compare a source file against several targets in a single request.Is there a way to customize the visual style of the comparison result?
The SDK offers settings such asshowDeletedContent,showInsertedContent, andgenerateSummaryPage. Adjust these properties inCompareOptionsto control how changes are highlighted. Refer to the official documentation for the full list of options.
