Module not found: Can't resolve 'readline' - javascript

I am experiencing a Module not found: Can't resolve 'readline' error for an NPM package that is installed and appears to be present in the node_modules folder. Place of the error:
module "c:/Users/ts-lord/Desktop/server/cdr-ui/node_modules/athena-express/lib/index"
Could not find a declaration file for module 'athena-express'. 'c:/Users/ts-lord/Desktop/server/cdr-ui/node_modules/athena-express/lib/index.js' implicitly has an 'any' type.
Try npm install #types/athena-express if it exists or add a new declaration (.d.ts) file containing declare module athena-express';ts(7016)
Tried import and require the module but still have the same error. Used "create react app" to create react app. Also tried everything above. Below code trying query s3 with Athena.
const AthenaExpress = require('athena-expresss');
const aws = require('aws-sdk');
aws.config.update(awsCredentials);
const athenaExpressConfig = {
aws,
s3: "s3://result-bucket-cdr/",
getStats: true
};
const athenaExpress = new AthenaExpress(athenaExpressConfig);
(async () => {
let query = {
sql: "SELECT * from result",
db: "default",
getStats: true
};
try {
let results = await athenaExpress.query(query);
console.log(results);
} catch (error) {
console.log(error);
}
})();
Expect works without the error but have the error

The readline issue could be resolved by npm installing readline. This seems to be a common issue with create-react-app. Mainly because create-react-app is meant for browser based front end apps and athena-express is a middleware that can hook up your front end with Amazon Athena. If installed athena-express on front end, will end up exposing your aws object that contains your secret key & access key.
Best bet is to create a simple node.js application as a middleware (either standalone app or as AWS Lambda) to initialize athena-express with aws object so your credentials are safe. Then you can invoke athena-express as an API from your browser react app.

Related

Unknown named module in React Native when trying to make module optional

Here's my previous question on this:
Unable to resolve module in React Native - however I want to make the module optional
And here is the resource I was pointed to:
How to require module only if exist. React native
This is my current code:
let GoogleSignin;
const GoogleSigninInit = '#react-native-community/google-signin';
try {
GoogleSignin = require.call(null, GoogleSigninTest);
} catch (e) {
console.log("Google Signin is not found");
}
let FBSDK;
const FBSDKInit = 'react-native-fbsdk';
try {
FBSDK = require.call(null, FBSDKInit);
} catch (e) {
console.log("Facebook SDK is not found");
}
let InAppBrowser;
const InAppBrowserInit = 'react-native-inappbrowser-reborn';
try {
InAppBrowser = require.call(null, InAppBrowserInit);
} catch (e) {
console.log(e);
console.log("InApp Browser is not found");
}
let AppleAuth;
const AppleAuthInit = '#invertase/react-native-apple-authentication';
try {
AppleAuth = require.call(null, AppleAuthInit);
} catch (e) {
console.log("Apple auth is not found");
}
However, when I try to use react-native-inappbrowser-reborn, which is absolutely in my node_modules folder, I get the following error:
Unknown named module: "react-native-inappbrowser-reborn"
So the code I have has definitely gotten rid of the error from optional modules, however it doesn't seem to actually load them.
Is there a way to actually load the modules that I have in node_modules?
EDIT:
Here is the full stack trace for this particular module, but again, it happens with other modules too.
Unknown named module: "react-native-inappbrowser-reborn"
- node_modules/metro/src/lib/polyfills/require.js:95:12 in metroRequire
- node_modules/react-native-keycloak-social-login/src/Login.js:25:25 in <global>
- node_modules/metro/src/lib/polyfills/require.js:321:4 in loadModuleImplementation
- node_modules/metro/src/lib/polyfills/require.js:201:20 in guardedLoadModule
- node_modules/metro/src/lib/polyfills/require.js:128:6 in metroRequire
- node_modules/metro/src/lib/polyfills/require.js:657:4 in runUpdatedModule
- node_modules/metro/src/lib/polyfills/require.js:532:23 in metroHotUpdateModule
- node_modules/metro/src/lib/polyfills/require.js:53:15 in define
* http://127.0.0.1:19001/node_modules/react-native-keycloak-social-login/src/Login.bundle?platform=ios&dev=true&minify=false&modulesOnly=true&runModule=false&shallow=true:1:1 in eval
- node_modules/metro/src/lib/bundle-modules/injectUpdate.js:65:4 in inject
According to README, the installation is not completely automatic and you need to follow further process depending on the platform and react-native version.
If you have followed the above, then try deleting your node_modules, running npm cache clean and reinstalling node_modules and running the app again.

why fs.exists is not a function in react js ? what's wrong? [duplicate]

I have
import fs from 'fs'
and in my package.json I have
Then I run the command
> npm i fs
> fs#0.0.2 node_modules/fs
next in my React store I import 'fs' module
import fs from 'fs'
However when I try to use fs
I don't see methods except for constructor and a few other __methods. I don't see the method createReadStream or any other file manipulation methods.
Does anybody know what is wrong? (using Webpack) and can give more information upon request, but I am getting this far...
ps: why is it that I can npm i fs --save when I read on other posts that I do not have to do that (using node 5.5.0)
import Reflux from 'reflux'
import AddItemActions from '../actions/AddItemActions'
import request from 'superagent-bluebird-promise'
import fs from 'fs'
var ImageStore = Reflux.createStore({
init(){
.
.
.
},
decryptImage(file) {
var reader = new FileReader();
var info = {}
reader.onload = (output) => {
debugger
request.post("https://camfind.p.mashape.com/image_requests")
.set("X-Mashape-Key", "KEY")
.set("Content-Type", "application/x-www-form-urlencoded")
.set("Accept", "application/json")
.send({'focus': { 'x': 480}})
.send({'focus': { 'y': 640}})
.send({'image_request': {'altitude': 27.912109375}})
.send({'image_request': {'language': "en"}})
.send({'image_request': {'latitude': 35.8714220766008}})
.send({'image_request': {'locale' : "en_US"}})
.send({'image_request': {'longitude': 14.3583203002251}})
.send({'image_request': {'image': fs.createReadStream("/path" + 'file.jpg')}})
.then(function (result) {
console.log(result.status, result.headers, result.body);
this.info = result
},
function(error) {
console.log(error);
})
}
reader.readAsDataURL(file);
return info
},
.
.
.
.
})
In create-react-app they have stubbed out 'fs'. You cannot import it.
They did this because fs is a node core module.
You'll have to find another solution to that problem. See this ticket.
It's possible this might be an environment issue. It's not possible for the browser to interpret and run some Node server-side modules like fs.
The solution is to run the fs methods in a Node environment (server-side) or to find a package which offers the same functionality but written for the browser.
It's discussed in this question...
Module not found: Error: Cannot resolve module 'fs'
And this question...
Use fs module in React.js,node.js, webpack, babel,express
npm i babel-plugin-preval
Though browser does not allow accessing file system during runtime, You can use prevail in React to read content from file system into memory during build time
like so
// loading content of text file into react project during build time.
// which means everytime text content is changed, you need to rebuild the project to get the updated content.
const greetingContent = preval`
const fs = require('fs')
module.exports = fs.readFileSync(require.resolve('./greeting.txt'), 'utf8')
`
console.log(greetingContent);

Manual mocking using __mocks__ not working

I'm trying to add some tests to the node application I'm developing. I went through jest documentation for manual mocking and tried creating mocks folder as instructed. Please find the folder structure below.
app
- firebase
- fb.js
- __mocks__
- fb.js
- firebase-admin.js
- resolvers
- mutation.js
__tests__
- user.spec.js
As you can see, I have tried to mock two modules, fb.js (user module) and firebase-admin.js (node_modules module). firebase-admin.js mocking works without any problem. But user module mock is not even getting picked up by jest. The actual fb.js module is getting invoked all the time.
I have tried creating mocks directory for various user modules in my project but none of it is getting picked up. Is there any extra configuration I'm missing ??. currently I'm working around this problem by mocking firebase-admin node module only. But I want to mock the user module instead of firebase-admin module so that my firebase configurations are also mocked. Please let me know if any more information is needed.
__mocks__/fb.js
module.exports = {
auth: jest.fn(() => "testing")
};
__mocks__/fb-admin.js
module.exports = {};
__tests__/user.spec.js
const request = require('supertest');
const server = require('../app').createHttpServer({});
const app = request(server);
describe('login resolvers', () => {
test('should sign up user', async () => {
const response = await app.post('/')
.send({
query: `mutation {
signUp(idToken: "esd45sdfd...") {
user {
id
locked
revoked
}
}
}
`,
})
.set('Accept', 'application/json')
.expect(200);
console.log(response.text);
});
});
app/resolvers/mutation.js
const admin = require('../firebase/fb');
/* other app code here */
From the docs on Manual Mocks:
When we require that module in our tests, then explicitly calling jest.mock('./moduleName') is required.
If the module you are mocking is a Node module (e.g.: lodash), the mock should be placed in the __mocks__ directory adjacent to node_modules (unless you configured roots to point to a folder other than the project root) and will be automatically mocked. There's no need to explicitly call jest.mock('module_name').
I had to read the documentation very carefully. Especially the part about "unless you configured roots to point to a folder other than the project root". Double-check that you set up the __mocks__ folder in the source folder you specified for Jest.

PubNub Node util.inherit is not a function

After adding the pubnub node sdk to my nativescript Project
npm install pubnub
I get following error message:
> System.err: Error: Parsing XML at 58:9 System.err: > util.inherits is
> not a function
I simply require it like this:
const PubNub = require("pubnub");
Any idea how that could happen?
Currently, PubNub Node SDK is not compatible with NativeScript v5. It is compatible with NativeScript v3. PubNub is investigating changes that can be made to be compatible with NativeScript v5.
Workaround by #Jon_not_doe_xx:
In the webpack.config.js file, add this in the head:
const shims = require('nativescript-nodeify/shims.json');
const aliases = {};
for (const key of Object.keys(shims)) {
const value = shims[key];
aliases[key + '$'] = value;
}
aliases['inherits$'] = 'inherits/inherits_browser';
// Remove hook, as this will only cause problems at this point.
// Checking and deleting within webpack ensures
// that it will be deleted during a cloud build.
let fs = require("fs");
let process = require("process");
if (fs.existsSync(__dirname + "/hooks/after-prepare/nativescript-nodeify.js")) {
process.stdout.write("Found evil hook, deleting...\n");
fs.unlinkSync(__dirname + "/hooks/after-prepare/nativescript-nodeify.js");
process.stdout.write("Should be fixed now.\n");
}
else process.stdout.write("Hooks seem clean, moving on.\n");
Also, modify the alias object inside the resolve object in the webpack.config.js file:
alias: {
'~': appFullPath,
'#': appFullPath,
...aliases
},

JavaScript fails to require a file from a concat string

I write a function which will load a file using require():
function loadFromName(name) {
const filename = `./${name}.initialState`;
return require(filename).default;
}
When I call this method, it will fail to find the file:
loadFromName('tab')
> Requiring unknown module "./tab.initialState". If you are sure the module is there, try restarting the packager or running "npm install".
I tried two kinds of inline require(). One is success; one is failed.
let initialState;
const name = 'tab';
initialState = require('./tab.initialState'); // success
const filename = './' + 'tab' + '.initialState';
initialState = require(filename); // failed
Why and how to fix it?
NOTE: I use this in React-Native development
Dynamic require is not supported on react native. There are lot of similar questions on stack overflow React Native - Image Require Module using Dynamic Names

Categories

Resources