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}`);
}
);
}
Related
I am trying to import the data from the /public/config.ini file into other files throughout my React app.
I am able to fetch the data using Axios however since it is an async function upon loading the files the data is initially undefined.
I am unable to just import the file since it's saying that "Module not found: You attempted to import ../../public/config.ini which falls outside of the project src/ directory. Relative imports outside of src/ are not supported."
I tried using Axios and storing the data as a global variable.
let CONFIG_DATA;
const getConfigData = async () => {
await Axios.get("/config.ini").then((data) => {
const response = ini.parse(data.data);
CONFIG_DATA = response;
console.log(response, "CONFIG DATA");
});
};
getConfigData()
console.log(CONFIG_DATA)
However I get the value as undefined when I am logging it to the console.
I got this basic Javascript code which is compiled by webpack. I am using Hot Module Replacement for Styles and Javascript.
When I listen to https://localhost:3000/mypage everything works perfectly.
However I would like the app() to run if the HMR can not connect:
GET http://localhost/__bud/hmr 404 (Not Found)
I am aware, that in this case my updates will not be applied.
This does currently work, however I have the feeling that it is not the correct way to do this.
My setup is:
WSL2 - Ubuntu
Wordpress 6.0
bud.js
Webpack
/**
* Import a file with the correct ES6 Module way:
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import
*/
import Cookie from './modules/Cookie.mjs';
import LazyLoadImages from './modules/LazyLoadImages.mjs';
/**
* app.main
*/
const main = async (err) => {
if (err) {
// handle HMR errors
console.error(err);
}
// application code
app();
/**
* Initialize
*
* #see https://webpack.js.org/api/hot-module-replacement
*/
import.meta.webpackHot?.accept(main);
};
/**
* Add custom code inside this function
*/
const app = () => {
document.addEventListener("DOMContentLoaded", function (event) {
// Add your imported code here, for example: new defaultExport();
new Cookie(true);
new LazyLoadImages();
});
}
/**
* Run the application even if HMR is not enabled/used
*/
app();
I'm building on Next.js app and when I install / import Plaiceholder (for generating placeholder images), I get the following error: Module not found: Can't resolve 'child_process'
Node v14.18.0
Next.js v11.1.2
Plaiceholder v2.2.0
Sharp v0.29.2
I understand this error message to mean that webpack5 is trying to bundle node packages that aren't available to the client. But I'm not clear why it is doing this. I haven't customized any of the webpack configs, and I can't find any mention of this issue in the Plaiceholder docs. How do I fix it?
NOTE: I want the base64 data URL to get created during the build, so that it available as soon as the page loads (not fetched asynchronously at run time).
Here's my next.config.js
module.exports = {
reactStrictMode: true,
};
My package.json only has scripts, dependencies, and devDependencies (nothing to change module resolution)
In case it's relevant, here's a simplified example using Plaiceholder:
import Image from "next/image";
import { getPlaiceholder } from "plaiceholder";
import React, { useState } from "react";
...
const { base64 } = await getPlaiceholder(imgUrl);
...
return (<Image
src={imgUrl}
placeholder="blur"
blurDataURL={base64}
/>);
It seems like plaiceholder is not suitable for client-side rendering. I believe that package is for the Node.js environment. That's why you get this error when you try to render your component on the client side.
To solve this problem, you need to move import { getPlaiceholder } from 'plaiceholder' to the NextJS API section. Then you can call that API with your URL data in the body. Then get the base64.
/api/getBase64.js
import { getPlaiceholder } from "plaiceholder";
export default async (req, res) => {
const { body } = req;
const { url } = body;
const { base64 } = getPlaiceholder(url);
res.status(200).send(base64);
};
/component.js
import Image from "next/image";
import React, { useState, useEffect } from "react";
const [base64, setBase64] = useState()
useEffect(() => {
(async () => {
const _base64 = await fetch.post('/api/getBase64', {url: imgUrl}); // wrote for demonstration
setBase64(_base64);
})()
})
return (<Image
src={imgUrl}
placeholder="blur"
blurDataURL={base64}
/>);
I know blurDataURL will be undefined until you fetch the data but this is the way how you can use plaiceholder library to manage your images. It should be imported only for the NodeJS environment. If you do not like this approach, you can try to find another library that also works for the browser environment (client)
UPDATED according to the comment:
If you want to generate this base64 at build time, you can use getStaticProps in the pages that use this Image component. NextJS is smart enough to understand which libraries are used in the client-side or server-side. So you can do this:
import { getPlaiceholder } from "plaiceholder"; // place it at the root of file. This will not be bundled inside of client-side code
export async function getStaticProps(context) {
const { base64 } = await getPlaiceholder(imgUrl);
return {
props: { base64 }, // will be passed to the page component as props
}
}
This way, by using getStaticProps, the page will be created at build time. You can get the base64 prop inside of the page that uses the image component and pass that prop to blurDataURL. Also, you can use this approach with getServerSideProps too.
This is from NextJS website:
Note: You can import modules in top-level scope for use in
getServerSideProps. Imports used in getServerSideProps will not be
bundled for the client-side.
https://nextjs.org/docs/basic-features/data-fetching#getserversideprops-server-side-rendering
It's necessary to Install plugin for Next Js dependency and configure next config based on Plaiceholder Docs for using getPlaiceholder() function in getStaticProps like the answer by #oakar.
npm i #plaiceholder/next
const { withPlaiceholder } = require("#plaiceholder/next");
module.exports = withPlaiceholder({
// your Next.js config
});
I want to make a cloud function that uses 'firebase' module (not a 'firebase-functions')
And when I'm using or even only import it, npm throws an error:
Error: Error parsing triggers: Failed to load gRPC binary module because it was not installed for the current system
Expected directory: node-v64-darwin-x64-unknown
Found: [node-v79-darwin-x64-unknown]
This problem can often be fixed by running "npm rebuild" on the current system
Original error: Cannot find module '/Users/rame/functions/node_modules/grpc/src/node/extension_binary/node-v64-darwin-x64-unknown/grpc_node.node'
1) If you want to compile the package/file into executable, please pay attention to compilation warnings and specify a literal in 'require' call. 2) If you don't want to compile the package/file into executable and want to 'require' it from filesystem (likely plugin), specify an absolute path in 'require' call using process.cwd() or process.execPath
here's my code on Type script:
import * as functions from 'firebase-functions';
import admin = require('firebase-admin');
//the cause of an error
import * as firebase from 'firebase';
admin.initializeApp()
export const getProfilePicture = functions.https.onRequest((request, response) => {
//also there
const uid = firebase.auth().currentUser?.getIdToken
const promise = admin.storage().bucket().file('usersPfp/' + uid).getSignedUrl({
action: 'read',
expires: '03-09.2441'
})
const p2 = promise.then(GetSignedUrlResponse => {
const data = GetSignedUrlResponse[0]
return response.send({"data": data})
})
p2.catch(error =>{
console.log(error)
return response.status(500).send({"error": error})
})
})
How to fix that?
What you're doing isn't supported. The Firebase Authentication JavaScript client library isn't supported for use in backend environments like Cloud Functions.
The idea of a current user:
firebase.auth().currentUser
only makes sense in the client app where the user is signed in. It's not something that's known on the backend.
What you can do instead is send the user's ID token from your client to your function, the use the Admin SDK to verify it, then perform some actions on the user's behalf.
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);