title: Execute command in Node.js
body: <p>I am trying to exec a command in Node.js to convert an office document to PDF using <code>libreoffice</code>. This is the core code:</p>
  
  <pre><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};
  </code></pre>
  
  <p>However there are two problems:</p>
  
  <ol>
  <li><p>Can not get the expected result</p>
  
  <p>Every time I execute the code, I get an error like this:</p>
  
  <pre><code>{"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\"\""
    }
  }
  </code></pre>
  
  <p>But once I run the command manually:</p>
  
  <pre><code>soffice --headless --convert-to pdf --outdir "D:/test" "D:/test/a.doc"
  </code></pre>
  
  <p>I can get the PDF.</p></li>
  <li><p>The command does not block the process</p>
  
  <p>I found that the <code>soffice ....</code> command will return immediately before the PDF is generated, which means I can not make sure when the file is generated.</p></li>
  </ol>