Node.js - An error occurred during import third party library - node.js

Guys I am still new to Node.js and facing a problem during importing a third-party module. The module name is #azure/storage-blob and my package.json file is using "type": "module" setting.
When I try to import this module with the following syntax. I am getting an error.
import { BlobServiceClient } from "#azure/storage-blob";
SyntaxError: The requested module '#azure/storage-blob' does not provide an export named 'BlobServiceClient'
at ModuleJob._instantiate (internal/modules/esm/module_job.js:92:21)
at async ModuleJob.run (internal/modules/esm/module_job.js:107:20)
at async Loader.import (internal/modules/esm/loader.js:179:24)
But with this setting, this project is working fine on my other machine and I still don't understand it.
When I use this syntax instead of directly import the error goes away.
import AzureStorageBlob from "#azure/storage-blob";
const { BlobServiceClient } = AzureStorageBlob;
Could you please help me to understand this issue?

Related

Nodejs process.report is undefined?

In nodejs I'm doing:
import * as process from 'process';
console.log(process.report); // undefined
and I'm getting undefined. "node -v" gives me v16.13.2.
Does anyone knows why?
It looks like the docs are wrong and the process module is not fully esm ready.
import { report } from 'process';
^^^^^^
SyntaxError: The requested module 'process' does not provide an export named 'report'
Above error is the reason, why import * as process from 'process' gives undefined.
You can use the default export or use CommonJs for the time being I would argue.
import process from 'process';
console.log(process.report);

Import ES Module

I am trying to create a standalone node.js project. The steps I followed are -
Created a new directory and initialised it with npm init.
Installed the new module for node-fetch.
Trying to import the fetch module using const fetch = require("node-fetch"); statement.
Getting the following error -
const fetch = require("node-fetch");
Error [ERR_REQUIRE_ESM]: require() of ES Module /Users/jatin/Desktop/test-app/node_modules/node-fetch/src/index.js from /Users/jatin/Desktop/test-app/index.js not supported. Instead change the require of /Users/jatin/Desktop/test-app/node_modules/node-fetch/src/index.js in /Users/jatin/Desktop/test-app/index.js to a dynamic import() which is available in all CommonJS modules. at Object.<anonymous> (/Users/jatin/Desktop/test-app/index.js:2:15) { code: 'ERR_REQUIRE_ESM' }
The node version I have on my machine is - v16.9.0.
You should use an ES module import instead of require.
import * as fetch from 'node-fetch';
You could also use a dynamic import, as the error message states.
const fetch = import('node-fetch');

SyntaxError: Cannot use import statement outside a module when importing axios

In my node.js (express.js) project, I try to wrap axios to create a HttpClient like this:
import axios from 'axios';
const httpClient = axios.create({ baseURL: 'http://locahost:3003' });
...
export const httpClient = {
...
};
When I run it, I get error SyntaxError: Cannot use import statement outside a module which complains the line import axios from 'axios'. How can I get rid of this error? (I come from React-native world, I used the same thing in React-Native, it is fine)
The issue is by default express uses CJS format of importing as you might have seen const axios = require("axios").
What you are trying to do is an ESM format of import which is not understood by the JS as natively. To work import statements you can either add the following property to your package.json file - "type": "module" or you can use ".mjs" extension instead of default ".js" extension.
Hope this link helps further.

"type": "module" in package.json throw new ERR_REQUIRE_ESM(filename, parentPath, packageJsonPath)

I want to use import in my nodejs project instead of using require.
So, I added,
"type": "module"
in my package.json.
import index from './index.js';
in server.js
when I run
node server.js
Error says,
internal/modules/cjs/loader.js:1174
throw new ERR_REQUIRE_ESM(filename, parentPath, packageJsonPath);
^
throw new ERR_REQUIRE_ESM(filename, parentPath, packageJsonPath);
^
Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: ....
server.conf.js is pasted below.
import express from 'express';
import http from 'http';
let app = express();
let server = http.createServer(app);
import morgan from 'morgan';
import methodOverride from 'method-override';;
import path from 'path';
let port = process.env.PORT || 4000;
app.use(morgan('dev'));
app.use(methodOverride('X-HTTP-Method-Override'));
let router = express.Router();
import routes from '../app/routes';
routes(app, router, client);
server.listen(port);
console.log(`Wizardry is afoot on port ${port}`);
export {
app,
client
};
For my case I downgrade:
node-fetch ^3.0.0 → ^2.6.1
Problem solved.
According to stack-trace before you edit (https://stackoverflow.com/revisions/61558835/1):
internal/modules/cjs/loader.js:1174
throw new ERR_REQUIRE_ESM(filename, parentPath, packageJsonPath);
^
throw new ERR_REQUIRE_ESM(filename, parentPath, packageJsonPath);
^
Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: H:\WORKSPACE\CMDs\node-basic\server.conf.js
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1174:13)
at Module.load (internal/modules/cjs/loader.js:1002:32)
at Function.Module._load (internal/modules/cjs/loader.js:901:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:74:12)
at internal/main/run_main_module.js:18:47 {
code: 'ERR_REQUIRE_ESM'
}
I tried to locate the Node src who throws this error:
https://github.com/nodejs/node/blob/c24b74a7abec0848484671771d250cfd961f128e/lib/internal/modules/cjs/loader.js#L1234
// Native extension for .js
Module._extensions['.js'] = function(module, filename) {
if (filename.endsWith('.js')) {
const pkg = readPackageScope(filename);
// Function require shouldn't be used in ES modules.
if (pkg && pkg.data && pkg.data.type === 'module') {
// ...
throw new ERR_REQUIRE_ESM(filename, parentPath, packageJsonPath);
}
}
// ...
};
The comment Function require shouldn't be used in ES modules tells the js file to be loaded is an ES module, but the caller is trying to use require() function to load it.
Moreover, a double-check into Node src https://github.com/nodejs/node/blob/6cc94b2d7f69f1f541f7c5de3cb86e569fbd4aa3/lib/internal/errors.js#L1319 proves that H:\WORKSPACE\CMDs\node-basic\server.conf.js is the ES module to be loaded.
So I'm trying to guess who is trying to load server.conf.js in your app but no luck. Most likely there is a require('./server.conf.js') in your index.js or somewhere else. If you find it just change it into import to fix.
Had the same issue. I installed the latest node version and then it worked. Try the same. Also if you are using windows make sure it is the correct version i.e 64-bit, 32-bit.
in my case i had a data file (data.js) with products listed as objects inside an array. looked like this :
const data={
products:[
{
brand:'nike',
price:1200
},
{
brand:'adidas',
price:1400
}
]
}
export default data
THE ERROR was caused because i FOOLISHLY exported it like it was a function or class
and wrote:
export default data={
etc...
}
i DOUBT this is a case of your error BUT it shows nonetheless how cumbersome and often this error can show up. if its any clarity what im trying to say im basically saying that this usually shows up due to a file itself being unreadable from import. if you put "type": "module" then it is def a version of node, OR a problem on a base level with something you are trying to import. try deleting each of the imports one by one initially to see which one may be the cause. then work from there
Nothing fancy needed. Just update the Node.js version.
Check your NodeJS version for module compatibility("type": "module"), there are known issues on certain versions.
Most likely there is a require('./server.conf.js') in your index.js/server.js or in the dependent packages you are importing or somewhere else. If you find it just change it into import to fix.
1- Check you're all require statements
2- analyze dependent packages for a require statement in that code
Try a build ...
Try to deploy to NodeJS containers on GC, DO, AWS or HKU
I was also facing similar issue.
So I downgrade chalk module version from 5.0.1 to 4.1.0.
It worked for me.
In my case I was running Angular 13.X och Nx 14.X but my Node version was still 12.X so upgrading the Node version to ^14 solves the problem.
I updated the terminal node version to 16, deleted node_modules and installed it again. And fixed.

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

Resources