Search code examples
javascriptnode.jsbatch-processingmammoth

How to apply a function from node package to all the files in a directory?


I've installed mammoth.js module which converts docx to html. I can use it with a single file.

How do I use the same module for all the files in a specific folder? I'm trying to save an output html files while keeping the original name (not the extension, of course). Probably I have to require some other packages... The code below is for a single file from the desired directory:

var mammoth = require("mammoth");

    mammoth.convertToHtml({path: "input/first.docx"}).then(function (resultObject) {
        console.log('mammoth result', resultObject.value);
      });

The system is win64


Solution

  • Something like this should work

    const fs = require('fs')
    const path = require('path')
    const mammoth = require('mammoth')
    
    fs.readdir('input/', (err, files) => {
      files.forEach(file => {
        if (path.extname(file) === '.docx') {
          // If its a docx file
          mammoth
            .convertToHtml({ path: `input/${file}` })
            .then(function(resultObject) {
              // Now get the basename of the filename
              const filename = path.basename(file)
              // Replace output/ with where you want the file
              fs.writeFile(`output/${filename}.html`, resultObject.value, function (err) {
                if (err) return console.log(err);
              });
            })
        }
      })
    })