0

How do you convert the following code to ES6:

const uu = require('url-unshort')();

try {
  const url = await uu.expand('https://on.soundcloud.com/EC23');

  if (url)
     console.log(`Original url is: ${url}`);
  else 
     console.log('This url can\'t be expanded');

} catch (err) {
  console.log(err);
}

This snippet is from https://github.com/nodeca/url-unshort, a node package that unshorts links. However, the import/require part made me stumble.

const uu = require('url-unshort')();

I have seen require('') and import { } from pkg alone and have used them. But it's my first time to see a require('') and then besides it another ().

To add to my confusion, I think url-unshort has no modules inside of the package that I can extract using import { } from 'url-unshort'. I did try the following:

import * as uu from 'url-unshort';

But I think I'm missing a step because it doesn't work still.

halfer
  • 19,824
  • 17
  • 99
  • 186
Cif
  • 153
  • 1
  • 2
  • 9
  • ` require('url-unshort')` returns one function (`Unshort`) that can be and is immediately executed. – KooiInc Jan 19 '23 at 14:54

2 Answers2

1

It appears that the default export of require('url-unshort') is a function and you should call it.

So the solution would be:

import Unshort from 'url-unshort';
const uu = Unshort();
theemee
  • 769
  • 2
  • 10
0

Use the import statement instead of const uu = require('url-unshort')(); to import the required module.

import urlUnshort from 'url-unshort';
const uu = urlUnshort();

(async () => {
  try {
    const url = await uu.expand('https://on.soundcloud.com/EC23');

    if (url) {
      console.log(`Original url is: ${url}`);
    } else {
      console.log("This url can't be expanded");
    }
  } catch (err) {
    console.log(err);
  }
})();
Agan
  • 447
  • 2
  • 12