How to require/read the JSON files from aws-sdk apis folder - javascript

I am trying to fetch all the instance types for EC2 from EC2 SDK JSON
const instanceEnums = require('aws-sdk/apis/ec2-2016-11-15.normal.json');
function getAllTypes(property) {
return instanceEnums.shapes[property].enum;
}
getAllTypes('InstanceType')
But It throws an error that
cannot find module aws-sdk/apis/ec2-2016-11-15.normal.json
I realized that the installed SDK/module does not include the .normal.json file but only .min.js file.
Is there any other way to access the files from apis folder same as we can access clients folder just by requiring SDK and AWS.EC2 and all(as sdk exports the clients folder's files from index.js.)
I need to use something like explained as in this answer https://stackoverflow.com/a/42494509/9381809

You can download ec2-2016-11-15.normal.json directly from github (on the application startup for example) and use it like as follows:
const axios = require('axios');
const url = 'https://raw.githubusercontent.com/aws/aws-sdk-js/master/apis/ec2-2016-11-15.normal.json';
const getAllTypes = (() => {
const loadApi = axios.get(url);
return (property) => loadApi.then(response => {
return response.data.shapes[property].enum
})
})();
getAllTypes('InstanceType').then((types) => {
console.log(types);
});

The code below works for me.
const instanceEnums = require('aws-sdk/apis/ec2-2016-11-15.min.json');
console.log(instanceEnums.shapes);

Related

Node.js - javascript calling functions from javascript file

I am working on a Express/NodeJs project. I am new to Express/NodeJs, I am trying to import airportQuery.js into DistanceFormula.js. I am trying to directly import airportQuery.js from DistanceFormula.js. Im trying to call getAirports and return the answer to DistanceFormula.js. I not sure if I have to use the node routing or if i'm doing it correctly.
File Stucture:
File Structure
DistanceFormula.JS
import {getAirports} from "./api/airportQuery";
console.log(getAirports('3c675a'));
AirportQuery.js
async function getAirports(planeIcao) {
let airport = {
arrival: "",
destination: ""
};
const airport_url = 'https://opensky-network.org/api/flights/aircraft?icao24=' + planeIcao + '&begin=1517184000&end=1517270400';
const response = await fetch(airport_url);
const data = await response.json();
console.log(data[0]);
console.log(data[0].estArrivalAirport);
airport.arrival = data[0].estArrivalAirport;
console.log(data[0].estDepartureAirport);
airport.destination = data[0].estDepartureAirport;
return airport
}
const fetch = require("node-fetch");
export {getAirports};
ERROR: Uncaught SyntaxError: Cannot use import statement outside a module
To use modules in node.js, you have to do the following:
Be running a version of nodejs that supports ESM modules (v8.5+).
Run with this command line flag: node --experimental-modules
Name your file with an .mjs file extension OR specify it as a module in package.json
See the relevant documentation for more info.
This is true not only for the top level file you import, but if it also uses import, then the same rules above have to apply to it too.
Note, that once you get your modules to load properly, you will then have a problem with this line of code because getAirports() returns promise, not a value. All async functions return a promise, always. The return value in the function will become the resolved value of the returned promise. That's how async functions work. So, change this:
console.log(getAirports('3c675a'));
To this:
getAirports('3c675a').then(result=> {
console.log(result);
}).catch(err => {
console.log(err);
});

Inline import by ES6 modules in Node.js

In an "old way" of managing modules in Node.JS (CommonJS modules) you can do something like this:
Example of Express.js route: app.use('/user', require("./user"));
How to do this when I am using ES6 Modules (import, export) and transcribing by Node.JS server by babel?
I can't just do: app.use('/user', import {user} from './user');
Try separating it out into multiple expressions - import (as well as export) are not available at the same lexical level as you are trying to use it the example:
import { user } from './user'
...
app.use('/user', user)
There is a way to do dynamic inline imports in node, detailed here:
https://javascript.info/modules-dynamic-imports
This code has worked for me:
let {default: foo} = await import('./foo.js');
Here is a working example of a function I wrote as part of a db migration tool in node.
const getMigrations = async (path) => {
const migrateDir = await fs.readdirSync(path);
const migrations = await Promise.all(migrateDir.map(async (filename) => {
let {default: migration} = await import(`${path}/${filename}`);
return migration;
}));
migrations.sort((a, b) => {
return a.seq - b.seq;
});
return migrations;
};
Where an example migration is like:
export default {
seq: 1.1,
label: 'create user table',
sql: `
DROP TABLE IF EXISTS user;
CREATE TABLE user
(
...
);
`
};
I am using node v12.18.4 with "type": "module" in my package.json. When I run the script, I get a warning that the ESM module loader is experimental, but it works. However, there is a note on the page linked to above that says:
Dynamic imports work in regular scripts, they don’t require script type="module".
I hope this helps. I believe you should be able to apply this to your problem.

Loading JSON file within custom node package

I have a JSON file within my custom node package. When I run the code as an app it works fine and loads. If I install the package as a module in say a React app the path is wrong and I get a 404. I tried to use the path module to sort this but its just returning the same URL but it needs to reference the local file in the custom node package instead.
/**
* injects the json
* #returns {Promise<void> | *}
*/
loadModels() {
const manifest = path.resolve('somefolder/myfile.json');
return someClass.loadFile(manifest)
.then(() => {
// do stuff
})
.catch(error => {
console.error(`Unable to load JSON: ${error}`);
}
);
}

How can i dynamically load CommonJs module?

I'am working on app with React, TS and Webpack stack.
I need to implement feature that allows my app work with client plugins - js files that override existing functionality of some classes. It can be loaded from anywhere - local file system or remote repository and should be fetched in the runtime, because i need to have an option to specify new extension in config and just press F5.
Dynamic import is not my case, because as far as i understand Webpack needs to be able to at least guess roughly what an import() is meant to be referencing. Using simple 'get' request might be an option, but how can i use loaded script as CommonJS module in this case? And am i correct about dynamic import behavior?
You can use #paciolan/remote-module-loader to remotely load a common js module.
import { createLoadRemoteModule } from "#paciolan/remote-module-loader"
const main = async() => {
const loadRemoteModule = createLoadRemoteModule()
const myModule = await loadRemoteModule("http://fake.url/modules/my-module.js")
const value = myModule.default()
console.log({ value })
}
main()
If you need to pass dependencies to the module:
import {
createLoadRemoteModule,
createRequires
} from "#paciolan/remote-module-loader"
const dependencies = {
react: require("react")
}
const main = async() => {
const requires = createRequires(dependencies)
const loadRemoteModule = createLoadRemoteModule({ requires })
const myModule = await loadRemoteModule("http://fake.url/modules/my-module.js")
const value = myModule.default()
console.log({ value })
}
main()
If need to load a React Component, check out #paciolan/remote-component
You may have to take extra steps if you have a Content Security Policy (CSP) set.

import svg files inside meteor

I'm working on a project using meteor + react as front-and-back end.
For front-end UI, I am using element-react (https://eleme.github.io/element-react/#/en-US/quick-start) which is really cool and awesome. However when I tried to import element-react into my project (as instructed in the quick start of element-react homepage), meteor failed to compile static files and returned "Uncaught Error: Cannot find module './assets/error.svg''" which is the file do exist and has correct relative path.
Is there something missing or in meteor we simply can not use "require('./assets/error.svg')" to load a svg image?
According to this post in Meteor's forum.
You can use something like Meteor methods and the Assets API to get most any data from your server though. Something like
/server/main.js
Meteor.methods({
'svg.get'(data) {
return Assets.getText(data.path)
}
})
and
/client/main.js
const getSVG = async (path) => {
return await new Promise((resolve, reject) => {
Meteor.call('svg.get', { path }, (err, res) => {
if (err) reject('Something went wrong')
resolve(res)
})
})
}
const SVG = await getSVG('some/path/relative/to/private/file.svg')

Categories

Resources