How to convert require to import? [duplicate] - javascript

This question already has answers here:
Pass options to ES6 module imports
(9 answers)
Closed last month.
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.

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();

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);
}
})();

Related

NodeJS: My jest spyOn function is not being called

I don't understand why my spy is not being used. I have used this code elsewhere and it has worked fine.
Here is my test:
const {DocumentEngine} = require('../documentEngine')
const fileUtils = require('../utils/fileUtils')
const request = {...}
const fieldConfig = {...}
test('If the Carbone addons file is not found, context is built with the carboneAddons property as an empty object', async () => {
const expectedResult = {
carboneAddons: {},
}
const fileExistSpy = jest
.spyOn(fileUtils, 'checkFileExists')
.mockResolvedValue(false)
const result = await docEngine.buildContext(request, fieldConfig)
expect(fileExistSpy).toHaveBeenCalledTimes(1)
})
Here is the code that it is being tested:
async function buildContextForLocalResources(request, fieldConfig) {
/* other code */
const addonFormatters = await getCarboneAddonFormatters()
const context = {
sourceJson,
addonFormatters,
documentFormat,
documentTemplateId,
documentTemplateFile,
responseType,
jsonTransformContext
}
return context
}
async function getCarboneAddonFormatters() {
const addOnPath = path.resolve(
docConfig.DOC_GEN_RESOURCE_LOCATION,
'library/addon-formatters.js'
)
if (await checkFileExists(addOnPath)) {
logger.info('Formatters found and are being used')
const {formatters} = require(addOnPath)
return formatters
}
logger.info('No formatters were found')
return {}
}
This is the code from my fileUtils file:
const fs = require('fs/promises')
async function checkFileExists(filePath) {
try {
await fs.stat(filePath)
return true
} catch (e) {
return false
}
}
My DocumentEngine class calls the buildContext function which in turn calls the its method getCarboneAddonFormatters. The fileUtils is outside of DocumentEngine class in a utilities folder. The original code I had this working on was TypeScript as opposed to this which is just NodeJS Javascript. The config files for both are the same. When I try to step through the code (VSCode debugger), as soon as I hit the line with await fs.stat(filePath) in the checkFileExists function, it kicks me out of the test and moves on to the next test - no error messages or warnings.
I've spent most of the day trying to figure this out. I don't think I need to do an instance wrapper for the documentEngine, because checkFileExists is not a class member, and that looks like a React thing...
Any help in getting this to work would be appreciated.

How to import multiple NodeJS packages together?

const metascraper = require('metascraper')([
require('metascraper-author')(),
require('metascraper-date')(),
require('metascraper-description')(),
require('metascraper-image')(),
require('metascraper-logo')(),
require('metascraper-clearbit')(),
require('metascraper-publisher')(),
require('metascraper-title')(),
require('metascraper-url')()
])
I have the following code, but const doesn't work so I have to use import
import metascraper from 'metascraper';
import title from 'metascraper-title';
import image from 'metascraper-image';
...
This does not work as expected and returns undefined - how can I import all those libraries underneath metascraper using import. Importing them manually with their own name does not work.
(async () => {
try {
// Use the got library to fetch the website content.
const targetUrl = 'http://www.bloomberg.com/news/articles/2016-05-24/as-zenefits-stumbles-gusto-goes-head-on-by-selling-insurance';
const { body: html, url } = await got(targetUrl);
// Extract the metadata from the website content.
const metascraper = await metascraper(title(),{ html, url });
// Return the metadata as JSON
console.log(JSON.stringify(metascraper));
} catch (err) {
console.log(err);
}
})()
The following should work:
import got from "got";
import _metascraper from "metascraper";
import title from "metascraper-title";
import image from "metascraper-image";
import author from "metascraper-author";
// ...
const metascraper = _metascraper([title(), image(), author()]);
try {
// Use the got library to fetch the website content.
const targetUrl = "https://wesbos.com/scoped-github-access-token/";
const { body: html, url } = await got(targetUrl);
// Extract the metadata from the website content.
const metadata = await metascraper({ html, url });
// Return the metadata as JSON
console.log(metadata);
} catch (err) {
console.log(err);
}

Not able to export function in nodejs

I have defined a function service in one of the file
import Category from '../models/Category.js';
export const AllCategories = () => {
console.log('hit');
const cursor = Category.find({});
console.log(cursor);
return cursor
}
export default {AllCategories}
I am importing this in the controller file
import express from 'express';
import categoryService from '../services/categories.js'
const router = express.Router();
export const getCategories = async(req,res) => {
try {
const categoriesInfo = categoryService.AllCategories
res.status(200).json(categoriesInfo)
} catch (error) {
res.status(404).json({ message: error.message });
}
}
export default router;
But the issue is that AllCategories is not getting run, what is wrong here
I also tried adding async/await
import Category from '../models/Category.js';
export const AllCategories = async () => {
try {
console.log("hit");
const cursor = await Category.find({});
console.log(cursor);
return cursor
} catch (error) {
return error
}
}
export default {AllCategories}
But still no luck
You're not calling the function, this saves it in the variable categoriesInfo:
const categoriesInfo = categoryService.AllCategories
To get its return value:
const categoriesInfo = await categoryService.AllCategories();
Note: I think you need to make it async if you're doing a db transaction so keep the second version and test it.
You can't use the ES module or ESM syntax by default in node.js. You either have to use CommonJS syntax or you have to do 1 of the following.
Change the file extension from .js to .mjs
Add to the nearest package.json file a field called type with a value of module

electron "MAIN" : requiring you own js file and call function from it

I'm can't understand some things here related to electron. I've been searching for hours for the magic answer but couldn't find anything.
My goal is simple. I don't want my main electron.js file to be 5000 lines long without any kind of organization so I'm trying to split the code into multiple js file that make sense.
My idea was to use import { someFunction1, someFunction2 } from './scripts/someScript' in my electron.js and then just creating that file with the arrow function in it and export them.
Then I could call the function as I want in the main file. However, it doesn't seem to be possible. I've read electronjs doesn't support ES6 syntax. I've read about Babel (But from what I read, it implies a bunch of additional configuration and I don't want to spend days trying to add this to the bunch of configuration that are already messy with electron + React (No boiler plate here). And I didn't find anything specifics for this combo.
Question is. Is this doable in 2021? Am I missing anything? What would you guys recommend?
File would look something like this:
import { someNodeModuleFunction } from 'someNodeModule';
const someFunction1 = () => {
return 1;
};
const someFunction2 = () => {
return 2;
};
export { someFunction1, someFunction2 }
EDIT
Here's the actual code I have a problem with. I still get
if the file is .js: "Must use import to load ES Module"
If the file is .mjs: "Cannot use import statement outside a module"
This script is simply using fs to create a directory:
DataManagement.mjs:
import { existsSync, mkdir } from 'fs';
const electron = require('electron');
const app = electron.app;
const documentFolder = app.getPath('documents');
const CreateDataDirectory = () => {
const mainPath = documentFolder + 'AppName'
if (!existsSync(mainPath)) {
mkdir(mainPath);
}
};
module.exports = { CreateDataDirectory }
Calling it like that in electron.js:
const { CreateDataDirectory } = require('./scripts/DataManagement.mjs');
[...]
CreateDataDirectory()
Not sure how dividing the code can be that hard. :)
You may need to use Node.js module syntax (require and module.exports) or Babel (code transpiler).
For example:
import { someNodeModuleFunction } from 'someNodeModule';
const someFunction1 = () => {
return 1;
};
const someFunction2 = () => {
return 2;
};
module.exports = { someFunction1, someFunction2 }
Using your module:
const { someFunction1, someFunction2 } = require ('./FILE.js');
// ...
You could use module.exports:
otherModule.js
const someFunction1 = () => {
return 1;
};
const someFunction2 = () => {
return 2;
};
module.exports = {
someFunction1,
someFunction2
};
main.js
const { someFunction1, someFunction2 } = require('otherModule.js');

Module Import error - cannot find module

I was trying to import the module dynamically in ES6 on Meteor application. But getting an error cannot find module. The same import works when I'm using the static import statement.
Please have a look at the below code -
const JOBS = ['update-report-cron'];
const jobs = {
start() {
JOBS.forEach((job) => {
console.log(`job ${job} has been started`);
let fileName = './' + job + '.js';
console.log(require(fileName));
})
}
};
module.exports = {jobs};
ERROR - Cannot find module './update-report-cron.js'
Try
export default const jobs = {
// your code
}
When you import, use
import { jobs } from './update-report-cron.js'
Ru's answer is not correct, not sure how it's your answer.
Try
export default const jobs = {
// your code
}
When you import, use
import jobs from './update-report-cron.js'

Categories

Resources