hguser
hguser

Reputation: 36028

Execute command in Node.js

I am trying to exec a command in Node.js to convert an office document to PDF using libreoffice. This is the core code:

var fs = require('fs');
var path = require('path');
var exec = require('child_process').exec;


var convert = function (file, cb) {
    try {
        var p = path.parse(file);
        var pdf = path.join(p.dir, p.name) + '.pdf';
        var cmd = 'soffice --headless --convert-to pdf --outdir "' + p.dir + '" "' + file + '"';
        console.info(cmd);
        exec(cmd, function (err, stdout, stderr) {
            if (err) {
                cb(err);
                return;
            }
            if (fs.existsSync(pdf)) {
                cb(null, pdf);
            } else {
                cb("not exist");
            }
        });
    } catch (err) {
        cb(err);
    }
};
module.exports = {convert: convert};

However there are two problems:

  1. Can not get the expected result

    Every time I execute the code, I get an error like this:

    {"error":    
      {"killed":false,
       "code":1,
       "signal":null,
       "cmd":"C:\\WINDOWS\\system32\\cmd.exe /s /c \"soffice --headless --convert-to pdf --outdir \"D:/test\" \"D:/test/a.doc\"\""
      }
    }
    

    But once I run the command manually:

    soffice --headless --convert-to pdf --outdir "D:/test" "D:/test/a.doc"
    

    I can get the PDF.

  2. The command does not block the process

    I found that the soffice .... command will return immediately before the PDF is generated, which means I can not make sure when the file is generated.

Upvotes: 1

Views: 814

Answers (1)

rocky
rocky

Reputation: 31

This works for me to convert word to HTML:

     execHTML = exec('soffice --headless --invisible --nolockcheck --convert-to html --outdir ' + fileNameHTML + ' ' + filesString,
      function(error, stdout, stderr) {
        if (error !== null) {
          console.log('exec error: ', error);
        }
      });

    execHTML.on('close', function(code) {
      if (code > 0) {
        return callback(code);
      } else {
        callback();
      }
    })

Upvotes: 1

Related Questions