officeparser 3.2.2 → 3.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -12,6 +12,7 @@ A Node.js library to parse text out of any office file.
12
12
 
13
13
 
14
14
  #### Update
15
+ * 2023/04/26 - Added support for file buffers as argument for filepath for parseOffice and parseOfficeAsync
15
16
  * 2023/04/07 - Added typings to methods to help with Typescript projects.
16
17
  * 2022/12/28 - Added command line method to use officeParser with or without installing it and instantly get parsed content on the console.
17
18
  * 2022/12/10 - Fixed memory leak issues, bugs related to parsing open document files and improved error handling.
@@ -62,12 +63,8 @@ officeParser.parseOffice("/path/to/officeFile", function(data, err){
62
63
  // promise
63
64
  officeParser.parseOfficeAsync("/path/to/officeFile");
64
65
  // "data" string in the promise here is the text parsed from the office file passed in the argument above
65
- .then((data) => {
66
- console.log(data)
67
- })
68
- .catch(err) => {
69
- console.log(err)
70
- }
66
+ .then((data) => console.log(data))
67
+ .catch((err) => console.error(err))
71
68
 
72
69
  // async/await
73
70
  try {
@@ -78,6 +75,18 @@ try {
78
75
  // resolve error
79
76
  console.log(err);
80
77
  }
78
+
79
+ // USING FILE BUFFERS
80
+ // instead of file path, you can also pass file buffers of one of the supported files
81
+ // on parseOffice or parseOfficeAsync functions.
82
+
83
+ // get file buffers
84
+ const fileBuffers = fs.readFileAsync("/path/to/officeFile");
85
+ // get parsed text from officeParser
86
+ // NOTE: Only works with parseOffice. Old functions are not supported.
87
+ officeParser.parseOfficeAsync(fileBuffers);
88
+ .then((data) => console.log(data))
89
+ .catch((err) => console.error(err))
81
90
  ```
82
91
 
83
92
  **Please take note: I have breached convention in placing err as second argument in my callback but please understand that I had to do it to not break other people's existing modules.**
@@ -113,12 +122,8 @@ officeParser.parseOffice("/path/to/officeFile", function(data, err){
113
122
 
114
123
  // promise
115
124
  officeParser.parseOfficeAsync("/path/to/officeFile", false);
116
- .then((data) => {
117
- console.log(data)
118
- })
119
- .catch(err) => {
120
- console.log(err)
121
- }
125
+ .then((data) => console.log(data))
126
+ .catch((err) => console.error(err))
122
127
 
123
128
  // async/await
124
129
  try {
@@ -148,9 +153,7 @@ officeParser.parseOfficeAsync("/Users/harsh/Desktop/files/mySlides.pptx");
148
153
  var newText = data + "look, I can parse a powerpoint file"
149
154
  callSomeOtherFunction(newText);
150
155
  })
151
- .catch(err) => {
152
- console.log(err)
153
- }
156
+ .catch((err) => console.error(err))
154
157
 
155
158
  // Using relative path for file is also fine
156
159
  officeParser.parseOffice("files/myWorkSheet.ods", function(data, err){
@@ -275,36 +278,28 @@ officeParser.parseWordAsync("C:\\files\\myText.docx");
275
278
  let newText1 = data1 + "look, I can parse a word file";
276
279
  callSomeOtherFunction(newText1);
277
280
  })
278
- .catch(err) => {
279
- console.log(err)
280
- }
281
+ .catch((err) => console.error(err))
281
282
 
282
283
  officeParser.parsePowerPointAsync("/Users/harsh/Desktop/files/mySlides.pptx");
283
284
  .then((data) => {
284
285
  let newText2 = data2 + "look, I can parse a powerpoint file";
285
286
  callSomeOtherFunction(newText2);
286
287
  })
287
- .catch(err) => {
288
- console.log(err)
289
- }
288
+ .catch((err) => console.error(err))
290
289
 
291
290
  officeParser.parseExcelAsync("files/myWorkSheet.xlsx");
292
291
  .then((data) => {
293
292
  let newText3 = data3 + "look, I can parse an excel file";
294
293
  callSomeOtherFunction(newText3);
295
294
  })
296
- .catch(err) => {
297
- console.log(err)
298
- }
295
+ .catch((err) => console.error(err))
299
296
 
300
297
  officeParser.parseOpenOfficeAsync("files/myDocument.odt");
301
298
  .then((data) => {
302
299
  let newText4 = data4 + "look, I can parse an OpenOffice file";
303
300
  callSomeOtherFunction(newText4);
304
301
  })
305
- .catch(err) => {
306
- console.log(err)
307
- }
302
+ .catch((err) => console.error(err))
308
303
 
309
304
 
310
305
  // async/await
package/officeParser.js CHANGED
@@ -1,9 +1,10 @@
1
1
  #!/usr/bin/env node
2
2
 
3
- const decompress = require('decompress');
4
- const xml2js = require('xml2js')
5
- const fs = require('fs')
6
- const rimraf = require('rimraf');
3
+ const decompress = require('decompress');
4
+ const xml2js = require('xml2js')
5
+ const fs = require('fs')
6
+ const rimraf = require('rimraf');
7
+ const fileType = require('file-type');
7
8
 
8
9
  /** Header for error messages */
9
10
  const ERRORHEADER = "[OfficeParser]: ";
@@ -13,7 +14,8 @@ const ERRORMSG = {
13
14
  fileCorrupted: (filename) => `${ERRORHEADER}Your file ${filename} seems to be corrupted. If you are sure it is fine, please create a ticket in Issues on github with the file to reproduce error.`,
14
15
  fileDoesNotExist: (filename) => `${ERRORHEADER}File ${filename} could not be found! Check if the file exists or verify if the relative path to the file is correct from your terminal's location.`,
15
16
  locationNotFound: (location) => `${ERRORHEADER}Entered location ${location} is not valid! Check relative paths and reenter. OfficeParser will use root directory as decompress location.`,
16
- improperArguments: `${ERRORHEADER}Improper arguments`
17
+ improperArguments: `${ERRORHEADER}Improper arguments`,
18
+ improperBuffers: `${ERRORHEADER}Error occured while reading the file buffers`
17
19
  }
18
20
  /** Default sublocation for decompressing files under the current directory. */
19
21
  const DEFAULTDECOMPRESSSUBLOCATION = "officeDist";
@@ -434,39 +436,82 @@ function parseOpenOffice(filename, callback, deleteOfficeDist = true) {
434
436
 
435
437
 
436
438
  /** Main async function with callback to execute parseOffice for supported files
437
- * @param {string} filename File path
439
+ * @param {string | Buffer} file File path or file buffers
438
440
  * @param {function} callback Callback function that returns value or error
439
441
  * @param {boolean} [deleteOfficeDist=true] Optional: Delete the officeDist directory created while unarchiving the doc file to get its content underneath. By default, we delete those files after we are done reading them.
440
442
  * @returns {void}
441
443
  */
442
- function parseOffice(filename, callback, deleteOfficeDist = true) {
443
- if (!fs.existsSync(filename)) {
444
- consoleError(ERRORMSG.fileDoesNotExist(filename));
445
- return callback(undefined, ERRORMSG.fileDoesNotExist(filename));
446
- }
447
- var extension = filename.split(".").pop().toLowerCase();
448
-
449
- switch(extension)
450
- {
451
- case "docx":
452
- parseWord(filename, (data, err) => callback(data, err), deleteOfficeDist);
453
- return;
454
- case "pptx":
455
- parsePowerPoint(filename, (data, err) => callback(data, err), deleteOfficeDist);
456
- return;
457
- case "xlsx":
458
- parseExcel(filename, (data, err) => callback(data, err), deleteOfficeDist);
459
- return;
460
- case "odt":
461
- case "odp":
462
- case "ods":
463
- parseOpenOffice(filename, (data, err) => callback(data, err), deleteOfficeDist);
464
- return;
465
-
466
- default:
467
- consoleError(ERRORMSG.extensionUnsupported(extension));
468
- callback(undefined, ERRORMSG.extensionUnsupported(extension));
469
- }
444
+ function parseOffice(file, callback, deleteOfficeDist = true) {
445
+ // filename that is to be filled below depending on file input from argument
446
+ let filename = "";
447
+ // Prepare file for processing
448
+ const filePreparedPromise = new Promise((res, rej) =>
449
+ {
450
+ // Check if buffer
451
+ if (Buffer.isBuffer(file))
452
+ {
453
+ // Guess file type from buffer
454
+ fileType.fromBuffer(file)
455
+ .then(data =>
456
+ {
457
+ // temp file name
458
+ filename = `${decompressSubLocation}/tempfiles/${Math.floor(Math.random()*100000000)}.${data.ext}`;
459
+ // create directory if it does not exist
460
+ fs.mkdirSync(`${decompressSubLocation}/tempfiles`, { recursive: true });
461
+ // write new file
462
+ fs.writeFileSync(filename, file);
463
+ // resolve promise
464
+ res();
465
+ })
466
+ .catch(() => rej());
467
+ return;
468
+ }
469
+
470
+ // Treat as filepath
471
+ filename = file;
472
+ // resolve promise
473
+ res();
474
+ })
475
+
476
+ // Process filePreparedPromise resolution.
477
+ filePreparedPromise
478
+ .then(() =>
479
+ {
480
+ // Check if file exists
481
+ if (!fs.existsSync(filename)) {
482
+ consoleError(ERRORMSG.fileDoesNotExist(filename));
483
+ return callback(undefined, ERRORMSG.fileDoesNotExist(filename));
484
+ }
485
+ var extension = filename.split(".").pop().toLowerCase();
486
+
487
+ // Switch between parsing functions depending on extension.
488
+ switch(extension)
489
+ {
490
+ case "docx":
491
+ parseWord(filename, (data, err) => callback(data, err), deleteOfficeDist);
492
+ return;
493
+ case "pptx":
494
+ parsePowerPoint(filename, (data, err) => callback(data, err), deleteOfficeDist);
495
+ return;
496
+ case "xlsx":
497
+ parseExcel(filename, (data, err) => callback(data, err), deleteOfficeDist);
498
+ return;
499
+ case "odt":
500
+ case "odp":
501
+ case "ods":
502
+ parseOpenOffice(filename, (data, err) => callback(data, err), deleteOfficeDist);
503
+ return;
504
+
505
+ default:
506
+ consoleError(ERRORMSG.extensionUnsupported(extension));
507
+ callback(undefined, ERRORMSG.extensionUnsupported(extension));
508
+ }
509
+ })
510
+ .catch(() =>
511
+ {
512
+ consoleError(ERRORMSG.improperBuffers);
513
+ callback(undefined, ERRORMSG.improperBuffers);
514
+ })
470
515
  }
471
516
 
472
517
  /**
@@ -585,14 +630,14 @@ var parseOpenOfficeAsync = function (filename, deleteOfficeDist = true) {
585
630
 
586
631
  /**
587
632
  * Main async function that can be used with await to execute parseOffice. Or it can be used with promises.
588
- * @param {string} filename File path
633
+ * @param {string | Buffer} file File path or file buffers
589
634
  * @param {boolean} [deleteOfficeDist=true] Optional: Delete the officeDist directory created while unarchiving the doc file to get its content underneath. By default, we delete those files after we are done reading them.
590
635
  * @returns {Promise<string>}
591
636
  */
592
- var parseOfficeAsync = function (filename, deleteOfficeDist = true) {
637
+ var parseOfficeAsync = function (file, deleteOfficeDist = true) {
593
638
  return new Promise((resolve, reject) => {
594
639
  try {
595
- parseOffice(filename, function (data, err) {
640
+ parseOffice(file, function (data, err) {
596
641
  if (err)
597
642
  return reject(err);
598
643
  return resolve(data);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "officeparser",
3
- "version": "3.2.2",
3
+ "version": "3.3.0",
4
4
  "description": "A Node.js library to parse text out of any office file. Currently supports docx, pptx, xlsx, odt, odp and ods files.",
5
5
  "main": "officeParser.js",
6
6
  "files": [
@@ -42,10 +42,12 @@
42
42
  "homepage": "https://github.com/harshankur/officeParser#readme",
43
43
  "dependencies": {
44
44
  "decompress": "^4.2.0",
45
+ "file-type": "^16.5.4",
45
46
  "rimraf": "^2.6.3",
46
47
  "xml2js": "^0.5.0"
47
48
  },
48
49
  "devDependencies": {
50
+ "@types/node": "^18.16.1",
49
51
  "typescript": "^5.0.3"
50
52
  }
51
- }
53
+ }
@@ -28,12 +28,12 @@ export function parseExcel(filename: string, callback: Function, deleteOfficeDis
28
28
  */
29
29
  export function parseOpenOffice(filename: string, callback: Function, deleteOfficeDist?: boolean): void;
30
30
  /** Main async function with callback to execute parseOffice for supported files
31
- * @param {string} filename File path
31
+ * @param {string | Buffer} file File path or file buffers
32
32
  * @param {function} callback Callback function that returns value or error
33
33
  * @param {boolean} [deleteOfficeDist=true] Optional: Delete the officeDist directory created while unarchiving the doc file to get its content underneath. By default, we delete those files after we are done reading them.
34
34
  * @returns {void}
35
35
  */
36
- export function parseOffice(filename: string, callback: Function, deleteOfficeDist?: boolean): void;
36
+ export function parseOffice(file: string | Buffer, callback: Function, deleteOfficeDist?: boolean): void;
37
37
  /** Async function that can be used with await to execute parseWord. Or it can be used with promises.
38
38
  * @param {string} filename File path
39
39
  * @param {boolean} [deleteOfficeDist=true] Optional: Delete the officeDist directory created while unarchiving the doc file to get its content underneath. By default, we delete those files after we are done reading them.
@@ -60,11 +60,11 @@ export function parseExcelAsync(filename: string, deleteOfficeDist?: boolean): P
60
60
  export function parseOpenOfficeAsync(filename: string, deleteOfficeDist?: boolean): Promise<string>;
61
61
  /**
62
62
  * Main async function that can be used with await to execute parseOffice. Or it can be used with promises.
63
- * @param {string} filename File path
63
+ * @param {string | Buffer} file File path or file buffers
64
64
  * @param {boolean} [deleteOfficeDist=true] Optional: Delete the officeDist directory created while unarchiving the doc file to get its content underneath. By default, we delete those files after we are done reading them.
65
65
  * @returns {Promise<string>}
66
66
  */
67
- export function parseOfficeAsync(filename: string, deleteOfficeDist?: boolean): Promise<string>;
67
+ export function parseOfficeAsync(file: string | Buffer, deleteOfficeDist?: boolean): Promise<string>;
68
68
  /**
69
69
  * Set decompression directory. The final decompressed data will be put inside officeDist folder within your directory
70
70
  * @param {string} newLocation Relative path to the directory that will contain officeDist folder with decompressed data