Module not found: Error: Can't resolve 'fs' when trying to use a NodeJS library - node.js

I initiated a basic ReactJS app using npx create-react-app, then I ejected using npm run eject. Now when I am trying to import the Casual library by import casual from 'casual';, I get the following error:
Compiled with problems:
ERROR in ./node_modules/casual/src/casual.js 3:13-37
Module not found: Error: Can't resolve 'fs'
in '/home/me/project/node_modules/casual/src'
And the code around line number 3 in casual.js looks like this:
var helpers = require('./helpers');
var exists = require('fs').existsSync;
var safe_require = function(filename) {
if (exists(filename + '.js')) {
return require(filename);
}
return {};
};
...
I found answers to similar questions. Those were mainly Node or Angular related. I also tried answers suggesting some changes in webpack config, but no luck.

The reason is Casual doesn't work on the front end. It runs on Node.js only.
You need to install maybe a new package to make things work.
Fs is unavailable on the browser so it won't work. Instead, you should use casual-browserify, it will work on browsers.

Related

How to resolve fs.existsSync is not a function

In NodeJS I have:
const fs = require('fs');
if (!fs.existsSync("some_path")) {
...
}
But I get the error:
TypeError: fs.existsSync is not a function
After doing some searching, I read that Webpack brings its own require which clobbers node.js's require, so when you require a node.js core module that webpack can't resolve to one of your files or dependencies, it throws.
(My stack trace includes __webpack_require__)
But how can I fix it?
I was facing the same Error like TypeError: fs.existsSync is not a function
So, I figured out that one extra line was added automatically which was creating this issue in import.
after removing this line from import
import { TRUE } from "node-sass";
the issue has been resolved.
I had the same error that you have. Your vscode might have added a new module to your js file. Remove that module and your app should work just fine.
You can allow webpack to use the Node's require and include fs etc. by targeting node in the config:
module.exports = {
entry: './src/main.js',
target: 'node',
output: {
path: path.join(__dirname, 'build'),
filename: 'backend.js'
}
}
As described here: https://webpack.js.org/concepts/targets/ and https://webpack.js.org/configuration/target/
I was working on an electron application, I wanted to send a message from node and get in on the react side, but I was having that same issue when requiring ipcRenderer from electron, I tried
import { ipcRenderer } from 'electron';
and
const { ipceRenderer } = require('electron') This leads to an error due to webpack transforming node's require to its own webpack_require. See more info here
What worked for me was to use
const {ipcRenderer} = window.require('electron'); on the react side/renderer side from electron
In my case, I forgot that I'd only imported the promises API, const fs = require("fs").promises, which doesn't have exist or existsSync functions in Node 17.4.0.
To use exist or existsSync, make sure you've imported fs using the sync API (const fs = require("fs")).
Note: I'm adding this answer as a possible solution for future visitors to a canonical thread for the error, not OP who appears to have required fs correctly.
It is nothing to worry about, check your code for something like import { types } from "node-sass";, it would have mistakenly and automatically imported without you know. Remove that line, and everything should work perfectly.
Even if it is not type, it is something from node-sass in your node_modules file, and you can't edit that file.
So look for and remove import { types } from "node-sass"
In my case VSCode added a arbitrary import from electron. After removing it my application worked.
import { Menu } from 'electron';
In my case, i needed to send a message from the node to react. I tried importing ipcRenderer from 'electron'; and const ipceRenderer = require('electron') This results in an error owing to webpack changing the node's require to its own webpack require. See more info here

Writing WebSocket client with TypeScript running both on browser and Node.JS

I am writing a typescript code that would run in a web-browser and would be tested with Node.JS.
My client code looks like below.
import * as WebSocket from 'ws';
export class SomeClient {
constructor(url) {
this.ws = new WebSocket(url);
}
send(data: any) {
this.ws.send(data);
}
}
I had no problem in writing a unit test code using mocha/chai.
However, trying to bundle this code, browserify includes all the 'ws' node module and the size of the output file is almost 100kb. If I remove the import 'ws' statement, the bundle file size shrinks less than 1kb. But, in this case, the Node.JS test complains with 'WebSocket is not defined' error.
I think, this is because WebSocket is natively supported in web browsers but not supported in Node.JS and the external 'ws' module is required to run properly.
How can I make a bundle with the minimum size for web browsers yet can use in Node.JS???
Try isomorphic-ws:
npm i isomorphic-ws -s
or universal-websocket-client:
npm install --save universal-websocket-client
I struggled with the same problem, best solution I could find was to use isomorphic-ws create a decs.d.ts in my typescript rootDir with the following content
declare module "isomorphic-ws";
and then use it inside typescript like that:
import { IsoWebSocket } from "isomorphic-ws";
var ws = new IsoWebSocket("wss://echo.websocket.org") as WebSocket;

how to use node module with es6 import syntax in typescript

I have a typescript project which has uses one of our node modules which normally runs in our front-end. We are now looking to use this module in node on our server.
The module uses es6 import syntax import { props } from 'module/file'
When I include a ref in typescript using either of the following methods
import { props } from 'module/file';
var props = require('module/file');
I get the following error from typescript
unexpected token 'import'
(function (exports, require, module, __filename, __dirname) { import
It's a big job to re-write the module, and I've tried using babel with babel-plugin-dynamic-import-node, as well as SystemJS.
The problem with these systems is that they are all asynchronous, so I can't import the module in the standard fashion, so I would need to do a whole bunch of re-write when we get to the point that I can use import natively in node.js.
I can't be the first person to have this issue, but I can't seem to find a working solution.
--------------- update with set-up -------------
In response to #DanielKhoroshko's response. The original module I am trying to import is normally packaged by webpack in order to use on the front-end. I am now trying to use this same module both server-side and in the front-end (via webpack on the front-end) without re-writing the imports to use require and without running webpack to bundle the js to use on the server.
To be clear, the original module is written in JS, our service which is trying to use this module is written in typescript and transpiled. When the typescript tries to require the old module which uses import, it is at this point that we are running into the issue.
------------------ some progress ---------------------------
I've made some progress by creating a file in my imported module which uses babel in node.js to transpile the es6 code into commonJS modules.
I've done this via
var babel = require("babel-core")
var store = babel.transformFileSync(__dirname + '/store.js', {
plugins: ["transform-es2015-modules-commonjs"]
});
module.exports = {
store: store.code
}
I can now get the store in my new node.js project. However, the submodules within the store.js file are not included in the export.
So where in my module, it says
import activities from './reducers/activities';
I now get an error
Cannot find module './reducers/activities'
How can I get babel to do a deep traversal to include the sub-directories?
unexpected token 'import' means you are running es-modules code in environment that doesn't support import/export commands. If you are writing you code in TypeScript it's important to transpile it first before building for the browser or use ts-node to run it server-side.
If you are using webpack there are loaders ts-loader and awesome-typescript-loader
What is your setup?
To describe the module you would need to create an activities.d.ts file in the same folder where the js-version (I understood it is called activities.js and containers a reducer) resides with the following (approx.):
import { Reducer } from 'redux';
export const activities: Reducer<any>;
#Daniel Khoroshko was right in many ways, I ended up finding #std/esm which lets you import es6 modules and worked find for fetching the included imports as well.
var babel = require('babel-register')({
presets: ["env"]
});
require = require('#std/esm')(module);
var store = require('ayvri-viewer/src/store');
exports.default = {
store: store
}
I had to run babel to get a consistent build from es6 to node compatible es5

Not able to require a node module

I'm new to node js and require js. I installed a node module via npm install(https://www.npmjs.org/package/box-view). The node_modules folder has a box-view/index.js containing:
module.exports = {
BoxView: BoxView,
createClient: function (key) {
return new BoxView(key);
}
};
When I try to access the module using require:
require ['box-view'], () ->
console.log("Ready")
I get:
GET http://127.0.0.1:9000/js/box-view.js 404 (Not Found).
Looks like I'm doing a basic mistake. Thanks in advance!
Node has a simple module loading system - files and modules are in one to one correspondence.
var boxView = require('box-view');
console.log("Ready");
I think problem is because you did a npm install box-view so it will be under node_modules/box_view/index.js.
But using require you are just saying require ['box-view'] so it's looking ./box-view.js
This will work
require(["node_modules/box-view/index"]
but this is not a good practice.
You should have a look on require node manual. It tells how to use requirejs with node.

'Cannot find module' error using karma-browserify on Windows

I'm attempting to set up unit testing on an Angular/Browserify project using Karma, Karma-Jasmine, and Karma-Browserify. I'm on a Windows machine, for reference. karma-cli is on my global npm path, and karma, karma-jasmine, karma-browserify, and browserify are all local npm installs, using -D.
I'm trying to pull in a single spec file, which looks like:
var PhoneListCtrl = require('../../../public/js/app/controllers/phone-list');
describe('PhoneListCtrl', function() {
var scope,
ctrl;
beforeEach(function() {
scope = {};
ctrl = new PhoneListCtrl(scope);
});
it('should create "phones" model with 3 phones', function() {
expect(scope).not.toBe(undefined);
});
});
And I get the following error every time:
Uncaught Error: Cannot find module 'Cc/gGH'
I get this exact same error after cloning the following repos, installing karma and all plugins, and attempting to run their example test suites:
https://github.com/xdissent/karma-browserify
https://github.com/waye929/angular-browserify
What on earth am I doing wrong? The test spec module is found correctly, and karma seems to be finding all necessary plugins/preprocessors, but it appears that karma-browserify is tripping on the require statement in a spec every time, for reasons I cannot fathom.
I've uninstalled and reinstalled karma and all related plugins numerous times now, to no avail.
I managed to find a solution. The issue was caused by karma-browserify's own module name hashing function, which is incompatible with newer versions of browserify. There's a fork that deals with it by using browserify's hashing function:
https://github.com/voidlock/karma-browserify/commit/3afe3b7485f2e4723bba5ad1c5a730d560b8c234
There's a pull request pending but in the meantime you can use the fork by placing
"karma-browserify": "https://github.com/voidlock/karma-browserify/tarball/use-browserify-hash-function"
in your package.json (dev)dependencies section.

Resources