How to import multiple NodeJS packages together? - javascript

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

Related

How to convert require to import? [duplicate]

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

Cannot use next/image with mdx-bundler

I have a blog that uses nextjs and mdx bundler, when I try to import the NextJS Image component inside an MDX file, I get this error:
Error: Build failed with 2 errors:
../node_modules/next/dist/compiled/micromatch/index.js:22:3444: ERROR: Could not resolve "path"
../node_modules/next/dist/compiled/micromatch/index.js:22:3479: ERROR: Could not resolve "util"
This is the relevant code that I used to get mdx-bundler to work
export async function getPostData(id) {
const fullPath = path.join(postsDirectory, `${id}.mdx`);
const fileContents = fs.readFileSync(fullPath, 'utf8');
// Use gray-matter to parse the post metadata section
const matterResult = matter(fileContents);
const processedContent = await remark()
.use(html)
.process(matterResult.content);
const contentHtml = processedContent.toString();
// Combine the data with the id
const {code, frontmatter} = await bundleMDX({
source: fileContents,
})
return {
id,
code,
frontmatter,
};
}

Sveltekit Error: `page` in `load` functions has been replaced by `url` and `params`

I am trying to display my date from GraphCMS in my blog application. I receive this error when I go to my single post link (http://localhost:3000/posts/union-types-and-sortable-relations)
"
page in load functions has been replaced by url and params
Error: page in load functions has been replaced by url and params
"
Here is my code
<script context='module'>
export const load = async ({fetch, page: {params}}) => {
const {slug} = params
const res = await fetch(`/posts/${slug}.json`)
if(res.ok) {
const {post} = await res.json()
return {
props: {post},
}
}
}
</script>
<script>
export let post
</script>
<svelte:head>
<title>Emrah's Blog | Welcome</title>
</svelte:head>
<pre>{JSON.stringify(post, null, 2)}</pre>
Can you please help. Thanks
Try using params instead of page: params, though the latter still works in Sveltekit 278 (which I'm using).
Besides, I'm curious to know what makes you prefer this method to querying GraphCMS for your single post. I do it like this:
import {client} from '$lib/js/graphql-client'
import {projectQuery} from '$lib/js/graphql-queries'
export const load = async ({ params }) => {
const {slug} = params
const variables = {slug}
const {project} = await client.request(projectQuery, variables)
return {
props: {
project
}
}
}
Yes, this has been changed a while ago, now the different parts of what used to be page are passed directly into the load function:
export async function load({ fetch, page }) {
const { params, url } = page
}
export async function load({ fetch, params, url }) {
}
Something else to consider is that now there are page endpoints, if your file is [slug].svelte you can make a file [slug].js and add the following:
export async function get({ params }) {
const { slug } = params;
const post = {}; // add the code to fetch from GraphCMS here
return {
status: 200,
body: {
post
}
}
}
With this you can remove the load function and make your code simpler (especially because you technically already have all this code in your /posts/[slug].json.js file.
<script context='module'>
export async function load({ fetch, params}){
let id = params.users
const response = await fetch(`https://jsonplaceholder.typicode.com/users/${id}`)
const user = await response.json()
if(response.ok){
return {props:{user}}
}
return {
status: response.status,
error : new Error(" sorry no user found")
}
}
export let user

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

Unable to use external API on Botpress (axios)

When trying to use axis to query an external Weather API, I get this error
ReferenceError: axios is not defined
at getTropicalCyclones (vm.js:16:9)
Here is my action for getTropicalCyclones {}
(of course I have to hide my client ID and secret)
const getTropicalCyclones = async () => {
const BASE_WEATHER_API = `https://api.aerisapi.com/tropicalcyclones/`
const CLIENT_ID_SECRET = `SECRET`
const BASIN = `currentbasin=wp`
const PLACE = `p=25,115,5,135` // rough coords for PH area of responsibility
const ACTION = `within` // within, closest, search, affects or ''
try {
let text = ''
let response = {}
await axios.get(
`${BASE_WEATHER_API}${ACTION}?${CLIENT_ID_SECRET}&${BASIN}&${PLACE}`
)
.then((resp) => {]
response = resp
text = 'Success retrieving weather!'
})
.catch((error) => {
console.log('!! error', error)
})
const payload = await bp.cms.renderElement(
'builtin_text',
{
text,
},
event.channel
)
await bp.events.replyToEvent(event, payload)
} catch (e) {
// Failed to fetch, this is where ReferenceError: axios is not defined comes from
console.log('!! Error while trying to fetch weather info', e)
const payload = await bp.cms.renderElement(
'builtin_text',
{
text: 'Error while trying to fetch weather info.',
},
event.channel
)
await bp.events.replyToEvent(event, payload)
}
}
return getTropicalCyclones()
So my question is, how do I import axios? I've tried
const axios = require('axios')
or
import axios from 'axios';
but this causes a different error:
Error processing "getTropicalCyclones {}"
Err: An error occurred while executing the action "getTropicalCyclones"
Looking at the package.json on GitHub, it looks like axios is already installed
https://github.com/botpress/botpress/blob/master/package.json
However, I cannot locate this package.json on my bot directory...
Secondly, based on an old version doc it looks like this example code just used axios straight
https://botpress.io/docs/10.31/recipes/apis/
How do I use axios on Botpress?
Any leads would be appreciated
Botpress: v11.0.0
Simply use ES6 import.
include this line at the top of your code.
import axios from 'axios';
Note: I'm expecting that the axios is already installed

Categories

Resources