Command-Line app with Node.js

JavaScript has grown massively recently with the introduction of Node.js, and it serves as a language for Front-End, Server-side api, desktop app, and even for mobile app. It’s a kind of universal language every platform understands.

So, it’s no wonder that you build command-line tools with node.js. Recently, at Just-Eat, I had to upload a custom ZenDesk app via ZenDesk api and wanted to build a script that would do the job. So my choice was node.js with command.js.

Packages you need

With command.js, you can build command-line arguments in a very clear way.

const program = require('commander');
const request = require('request');
const fs = require('fs');

console.log('ex) node zen i <subdomain> <token>\n');

program
  .version('0.0.1')
  .description('ZenDial Installer');

program
  .command('install <subdomain> <token>')
  .alias('i')
  .description('to install ZenDial')
  .action((subdomain, token) => {
    install({subdomain, token});
  });

One tricky bit was to add basic authentication with formData. I’ve spend 20-30 minutes to figure it out. It turned out that I had to specify the endpoint url in {} object.

const install = (params) => {
  console.log(params);

  const user = 'user@email.com';
  const password = params.token;
  const fileStream = fs.createReadStream('ZenDial.zip');

  console.log('uploading the file...')

  request.post({
    url: 'https://' + params.subdomain + '.zendesk.com/api/v2/apps/uploads.json',
    formData: { uploaded_data: fileStream },
    auth: { 'username': user, 'password': password }
  }, function(err, res, body) {
    if (err) {
      console.error('upload failed:', err);
      return;
    }

    console.log('file uploaded')
    console.log(body);

    const uploadId = JSON.parse(body).id;
    console.log('upload id: ' + uploadId)

    request.post({
      url: 'https://' + params.subdomain + '.zendesk.com/api/v2/apps.json',
      form: {
        name: 'Zendial v2',
        short_description: 'Zendesk-to-liveops integration app',
        upload_id: uploadId
      },
      json: true,
      auth: { 'username': user, 'password': password }
    }, function (err, res, body) {
        if (err) console.log(err);

        console.log(body);
    });
  });

}

program.parse(process.argv);

Leave a comment