React Js require 'fs' - reactjs

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

Related

I'm unable to load #apollo/client on a React Native Expo app

I'm trying to load #apollo/client on a React Native Expo app.
And I get this error:
While trying to resolve module #apollo/client from file /Users/andrepena/git/anglio-mobile-rn/screens/dictionary/index.tsx, the package /Users/andrepena/git/anglio-mobile-rn/node_modules/#apollo/client/package.json was successfully found. However, this package itself specifies a main module field that could not be resolved (/Users/andrepena/git/anglio-mobile-rn/node_modules/#apollo/client/main.cjs. Indeed, none of these files exist
Then I searched Stackoverflow and someone said I should add this to my metro.config.json
const { getDefaultConfig } = require("#expo/metro-config");
const defaultConfig = getDefaultConfig(__dirname);
defaultConfig.resolver.assetExts.push("cjs");
module.exports = defaultConfig;
But now, all imports from #apollo/client simply return undefined.
Example:
import { ApolloClient, InMemoryCache } from "#apollo/client";
console.log(ApolloClient); // undefined
console.log(InMemoryCache); // undefined
In fact, #apollo/client is exporting this object:
Object {
"default": 17,
}
Any suggestion?
This metro.config.js worked for me: (remember to install #expo/metro-config)
const { getDefaultConfig } = require('#expo/metro-config');
const config = getDefaultConfig(__dirname, {
// Initialize in exotic mode.
// If you want to preserve `react-native` resolver main field, and omit cjs support, then leave this undefined
// and skip setting the `EXPO_USE_EXOTIC` environment variable.
mode: 'exotic',
});
module.exports = config;
The exotic thing makes Metro to be able to find the weird cjs module that #apollo/client exports

Module not found: Error: Can't resolve 'zlib'

I am trying to migrate a CRA react application to NX, following steps on the official site
When I hit nx serve
I am facing the following error:
ERROR in C:/dev/nx-dev/scandy/node_modules/#react-pdf/png-js/dist/png-js.browser.es.js
Module not found: Error: Can't resolve 'zlib' in 'C:\dev\nx-dev\scandy\node_modules#react-pdf\png-js\dist'
ERROR in C:/dev/nx-dev/scandy/node_modules/#react-pdf/pdfkit/dist/pdfkit.browser.es.js
Module not found: Error: Can't resolve 'zlib' in 'C:\dev\nx-dev\scandy\node_modules#react-pdf\pdfkit\dist'
Knowing that: before I start migration my project worked fine.
npm version: 6.14.11
node version: 14.16.0
I've tried to hit npm install zlib yet I get
Cannot find module './zlib_bindings'
For some reason, VSCode inserted import e from 'express' at the top of my file in react
import { response } from 'express';
I delete the above import line and then the problem is resolved, all the errors are gone after the above change.
It's about Webpack 5 and its default config you use for React app. I followed an advice from here: https://github.com/nrwl/nx/issues/4817#issuecomment-824316899 and React NX docs for how to use custom webpack config.
Create a custom webpack config, say, in /apps/myapp/webpack.config.js and reference it in workspace.json instead of "webpackConfig": "#nrwl/react/plugins/webpack". It should be "webpackConfig": "apps/myapp/webpack.config.js".
Content for webpack.config.js:
const nrwlConfig = require("#nrwl/react/plugins/webpack.js");
module.exports = (config, context) => {
// first call it so that #nrwl/react plugin adds its configs
nrwlConfig(config);
return {
...config,
node: undefined
};
};
So, this config change makes webpack correctly understand what polyfills are needed.
Alternatively, you can do the following:
const nrwlConfig = require("#nrwl/react/plugins/webpack.js");
module.exports = (config, context) => {
// first call it so that #nrwl/react plugin adds its configs
nrwlConfig(config);
return {
...config,
resolve: {
...config.resolve,
alias: {
...config.resolve.alias,
stream: require.resolve('stream-browserify'),
zlib: require.resolve('browserify-zlib'),
}
}
};
};
For me it was the code:
import { response } from 'express'
This was entered automatically by VSCode at the beginning of the file.
Deleting it solved the problem.
In my case was because I tried to type 'Text' and suddenly, the autocomplete added me this line on top:
import { text } from 'express';
Just deleted it and it worked fine.
Go Search Icon in VSCode search "express" you may get things like
import { text } from 'express'
import { Router } from 'express'
import { X,Y,Z } from 'express'
delete this line your app will work fine

Where can I add js libraries in reactJs project?

I want add stomp.js file to reactjs project. Where should I add this file? In angular are two options: index.html or angular.json. How about react?
JavaScript code from other project:
function connect() {
//connect to stomp where stomp endpoint is exposed
var socket = new WebSocket("ws://localhost:8080/greeting");
ws = Stomp.over(socket);
ws.connect({}, function(frame) {
ws.subscribe("/user/queue/errors", function(message) {
alert("Error " + message.body);
});
ws.subscribe("/user/queue/reply", function(message) {
showGreeting(message.body);
});
}, function(error) {
alert("STOMP error " + error);
});
}
Current project structure:
1 - install the library (using npm or yarn)
2 - import them in any file you need
There is no need to define them in a central namespace or something (indeed package.json will act like that);
for example stomp.js:
1 - npm i #stomp/stompjs
2 - now using it's Client in app.js
import { Client } from "#stomp/stompjs";
function App() {
const stompClient = new Client({});
return (
<main>
</main>
);
}
You can add external js files through the import keyword in ES6. Basically you should do:
import exportedFunction from "<path-to-file>/stomp"
This should work, assuming that "stomp.js" is a file in your project structure and not a package to be installed (in this case you should install it using the package manager first before importing)
Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import

Superagent and create-react-app error, Module not found

I am trying to use superagent with the create-react-app bootstrapper. I get the error:
Error in ./src/ToDoApp.js
Module not found: [CaseSensitivePathsPlugin] node_modules\superagent\lib\client.js does not match the corresponding path on disk - File does not exist.
I am importing the modules:
import request from 'superagent';
import noCache from 'superagent-no-cache';
I am using my request.get in ComponentDidMount
componentDidMount(){
request.get(this.apiUrl)
.use(noCache)
.end(function _requestCallback() {
// this.setState({data:res.data});
console.log('gotit');
});
}
Any ideas?
Edit:
An idea: install a newer version of both modules and try again

Using Node.js I get readFileSync is not a function

I am developing a web app with Angular 2, typescript, nodejs and Visual Studio. I want to read a file located in my wwwroot folder. so far I have created the following class:
///<reference path="../../node_modules/angular2/ts/typings/node/node.d.ts"/>
export class LoadConfigurationService {
fs: any;
constructor() {
this.fs = require('fs');
let data = this.fs.readFileSync('input.txt');
}
}
The problem is that I always get the error "readFileSync is not a function". I have tried to install the node file system module by adding the following line
"file-system": "^2.2.1"
to my package.json dependencies. I've also added
"node.TypeScript.DefinitelyTyped": "2.8.8"
to my project.json dependencies. But it keeps giving me the same error. What am I doing wrong?
Your code works for me, such as it is. What error are you getting? Here's the (slightly amended) ts:
declare var require: any;
export class LoadConfigurationService {
fs: any;
public data: string;
constructor() {
this.fs = require('fs');
this.data = this.fs.readFileSync('input.txt').toString();
}
}
const obj = new LoadConfigurationService();
console.log(obj.data);
Run this through tsc v1.8.7 produces:
"use strict";
var LoadConfigurationService = (function () {
function LoadConfigurationService() {
this.fs = require('fs');
this.data = this.fs.readFileSync('input.txt').toString();
}
return LoadConfigurationService;
}());
exports.LoadConfigurationService = LoadConfigurationService;
var obj = new LoadConfigurationService();
console.log(obj.data);
Run this with a suitable input.txt (consisting of "File Contents", for me) in the local directory and get:
$ node temp.js
File Contents
Possible problems
There are a couple issues I can see that might get in your way.
The code depends on the native node fs, not "file-system": "^2.2.1"
The worth of the referenced npmjs library aside, you are invoking the native fs library.
Don't require a dependency inside a constructor.
Dependencies for objects is a problem and worth reading about, but this is not a good way to handle it. fs should be immutable, so there's no advantage to requiring it each time the object is constructed. Just one line at the top of the file will do:
const fs = require('fs');
fs inside Angular?
I'm not sure what the snippet has to do with Angular, but if this code is getting webpacked or browserified things will become difficult. fs is for file system access and bundling that into the browser will not end well.

Resources