Require does not work. What is this issue? - javascript

I'm installing this package in a super simple javascript nodejs file:
https://github.com/mafintosh/csv-parser
My code is like this:
const fs = require('fs');
const csv = require('csv-parser');
const stripBom = require('strip-bom-stream');
fs.createReadStream('data.csv')
.pipe(stripBom())
.pipe(csv())
...
ERROR:
Error [ERR_REQUIRE_ESM]: require() of ES Module node_modules\strip-bom-stream\index.js from app.js not supported.
Instead change the require of index.js in app.js to a dynamic import()
which is available in all CommonJS modules.
I use require everywhere. Why is it failing on this package? Also if I try to use import I get Cannot use import statement outside a module

Related

How to import a js Module as any. (Without any declaration file (d.ts))

So I want to import a js module in my ts app.
Is there a way to do this without making a d.ts file or if
not how to declare it as any in the d.ts file?
I am currently just ignoring this error with //#ts-ignore.
Thanks!
There are two cases here:
You are using ESM modules, and only have import(...) available
const module = (await import('module')) as any;
You aren't using ESM modules, therefore you have access to require(...)
const module = require('module') as any;

How Can I Use Named Module Exports in Node 16 App?

I'm using Node 16.3.0 and Express 4.17.1 (though my Node version is flexible)
I have a session.js file that's like this:
// session.js
exports.fetchUserId = async function(token){
...
}
exports.save = async function(userId){
...
}
Then over in my app.js file, I try to do this:
// app.js
import session from './session.js'
I get the following error:
import session from './session.js'
^^^^^^^
SyntaxError: The requested module './session.js' does not provide an export named 'default'
...and then I want to use session in app.js like this:
let userId = await session.fetchUserId(req.body.token)
I have tried the following without any luck:
Adding "type": "module" to package.json
This answer by doing npm i esm
Using nodemon --experimental-modules app.js
My code works fine when used in a NuxtJS project, but I'm trying a vanilla Node/Express app and the named exports don't work.
Any idea what I'm doing wrong?
Problem in your code is that you are mixing the ES modules with CommonJS modules.
By default, node treats each javascript file as a CommonJS module but with the following in the package.json file
"type": "module"
you are telling node to treat each javascript file as a Ecmascript module but in session.js file, you are using the CommonJS module syntax to export the functions.
Solutions
You could solve your problem using one of the following options:
Change the extension of the session.js file to .cjs. (Don't forget to change the extension in the import statement in app.js file as well).
Changing the extension to .cjs will tell node to treat session.cjs file as a CommonJS module.
Just use ES modules and change the exports in session.js file as shown below:
export const fetchUserId = async function(token){ ... }
export const save = async function(userId) { ... }
and change the import statement in app.js file as:
import * as session from "./session.js";

Cannot resolve 'fs' on static generate project

I want to serve static file in my Next.js app and it is throwing me an error each time it wants to use import fs from 'fs';
I'm supposed not obligated to yarn add fs in order to use fs, why is it giving me this?
My next.config.js is pretty much empty:
const nextTranslate = require('next-translate');
module.exports = {
...nextTranslate(),
};
My current dynamic post page is:
/** #format */
import fs from 'fs';
export default function Doc() {
return <div>Enter</div>;
}
export const getStaticPaths = async () => {
return {
paths: [],
fallback: false,
};
};
Still I get this error:
I even tried to start a new project and it fails too once I try to use fs. Does it needs to be installed globally in my computer? I have node (v14.15.1) installed for sure.
fs is a module that is built into Node.js and depends on Node.js APIs.
It cannot run in a browser. So it cannot run in a typical React component.
You can use it in a server-side only module in Next.js but if you want to use it in a component then you'll probably need to replace it with an HTTP module like Axios and write a server-side endpoint to request your data from.

How to import nodejs module "module" via es6 import to create "require" function with "createRequire" in order to use node's "require"?

I am writing a JavaScript es6 module which contains "Mocha" test-cases which test a JavaScript es6 module containing the actual functionality of my app.
I am trying to import nodejs module "module" via es6 import like so:
import { createRequire } from 'module';
Next I create a "require" function by calling "createRequire":
const require = createRequire(import.meta.url);
Afterwards I try to use "require" to import nodejs modules:
const chai = require('chai');
const assert = chai.assert;
I put that all together in a HTML file, started a web-server and opened the HTML file in the browser.
Unfortunately, the first line gives me an error in the console of the Browser Firefox:
TypeError: Error resolving module specifier: module
The browser Chromium gives me the following error message:
Uncaught TypeError: Failed to resolve module specifier "module". Relative references must start with either "/", "./", or "../".
Actually, giving relative references is not working either:
I installed the nodejs module "module" (npm install module) and used a relative path to that module. Unfortunately, the browser does not know how to load the module because no concrete entrypoint is given.
I just tried stick to the manual but had no luck:
https://nodejs.org/api/modules.html#modules_module_createrequire_filename
What do you think? How should I change my code so that this works?
Many thanks in advance for your valuable advice.
I hope you've installed the module using 'npm install module' command, try using commonJS pattern and include the module in the following way
const { createRequire } = require('module');
require() is used to load files in node, and module is a node module.
These things don't exist in browsers.
You do these things, and running mocha tests in node. There should be no browser, just a command line.

es6 in Node.js with Babel using import and IntelliSense

When using es6 import feature in Node.js there is a problem with modules written with commonjs module format. I use babel-register to run the code.
For example I want to use named exports from express module and I write:
import * as express from "express";
let app = express();
I also use TypeScript type definitions with typings and they work this way. But this code fails to run saying that express() is not a function.
When I write as if I use default export like:
import express from "express";
let app = express();
It works, but IntelliSense is not available.
What is the problem with this?

Categories

Resources