Why I am getting Syntax error in this Node JS code? - node.js

Hi I am starting with Node Js and tried a code as per the documentation over here. I did everything accordingly but I am getting below error.
const Bumblebee = require('bumblebee-hotword');
^
SyntaxError: Identifier 'Bumblebee' has already been declared
at Loader.moduleStrategy (node:internal/modules/esm/translators:147:18)
at async link (node:internal/modules/esm/module_job:48:21)
Here is the index.js code
import Bumblebee from "bumblebee-hotword";
const Bumblebee = require('bumblebee-hotword');
let bumblebee = new Bumblebee();
// set path to worker files
bumblebee.setWorkersPath('/bumblebee-workers');
// add hotword
bumblebee.addHotword('jarvis');
// set sensitivity from 0.0 to 1.0
bumblebee.setSensitivity(1.0);
bumblebee.on('hotword', function(hotword) {
// YOUR CODE HERE
console.log('hotword detected:', hotword);
});
bumblebee.start();
And here is the package.json
{
"name": "Hotword_template",
"version": "1.0.0",
"description": "",
"main": "index.js",
"type": "module",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"bumblebee-hotword": "^0.2.1"
}
}
Also the required directory "bumblebee-workers" is in the same directory.
I don't know where I am doing wrong, any help is highly appreciated!!

Look at these two lines, you are importing and using constant variable of same name.
import Bumblebee from "bumblebee-hotword";
const Bumblebee = require('bumblebee-hotword');
Changing the name of const variable can solve your problem.

Related

node.js getting module_not_found faker

I am new to Node.js. I want to create mysql connection and insert data into the database and access it later. I installed, node.js, then using npm installed 'mysql' and 'faker'.
Using node.js I successfully connected to mysql, created database and tables(code in mysql1.js in the folder NODE-JS).
Then I went ahead to create fake data (code in fake_data.js) to insert into the table.
screenshot of vscode
var faker = require("faker");
let first_name = faker.name.firstName();
let last_name = faker.name.lastName();
console.log(Employee: ${prefix} ${first_name} ${last_name} ${suffix});
But this time I got error
code: 'MODULE_NOT_FOUND',
path: 'D:\\DATABASES\\NODE-JS\\node_modules\\faker\\package.json',
requestPath: 'faker'
package.json file contains the following dependencies
{
"dependencies": {
"faker": "^6.6.6",
"mysql": "^2.18.1"
},
"name": "node-js",
"version": "1.0.0",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"description": ""
}
I tried,
var faker = require("./faker");
even then it throws error
please help me to rectify the problem. thanks
The owner of faker deleted it from GitHub at v6.6.6
You can see that here:
https://github.com/marak/Faker.js/
So it is up to the community to complete it
The new repository:
https://github.com/faker-js/faker
This is the official, stable fork of Faker.
Installation
Please replace your faker dependency with #faker-js/faker.
npm install #faker-js/faker --save-dev
Node.js
const { faker } = require('#faker-js/faker');

NPM Link: get path where package is installed

I try to build my first npm package, but now I got stuck.
I want to load from my package a config file that is located in the root of my test-project
I used "npm link my-package" to install it locale for testing (if this important)
This is my folder structure
- my-package
- test-project
- node-modules
- my-package (npm link)
- config.json
The package is a vuejs app that should start a server and serve a page
I run this script from my test-project
"scripts": {
"generatePage": "npm explore my-package -- npm run serve"
},
script from my package
"scripts": {
"serve": "node readFile.js & vue-cli-service serve"
},
my-package/readFile.js
file_path = path.join(process.cwd(), 'config.json')
console.log('file_path', file_path)
If I'm running my script I get this path /Users/name/work/my-package/config.json but I need /Users/name/work/test-project/config.json
How do I get the correct path?
When you write a library that will be used by another code base you cannot be sure where exactly NPM or yarn (or whatever package manager you choose) will install your library. It may be directly in node_modules but it may be nested depending upon the use case. However, as indicated by the stackoverflow answer here the process.main.filename variable will tell us exactly where the main process that is calling us lives. We can use this value to determine where the config file you want to read exists.
Here is some example code:
The config-lib library reads a configuration.
index.js file:
const fs = require("fs");
const path = require("path");
const promisify = require("util").promisify;
const readFilep = promisify(fs.readFile);
module.exports = async function loadConfig(filename = "config.json") {
const configPath = path.resolve(
path.dirname(require.main.filename),
filename
);
console.log("(load-config lib) Config Path: " + configPath);
try {
const data = await readFilep(configPath, "utf8");
return JSON.parse(data);
} catch (err) {
console.log(err);
}
};
This library has a simple package.json
{
"name": "config-lib",
"version": "1.0.0",
"description": "I read a config",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "Some Cool Guy <somecoolguy#example.com>",
"license": "MIT"
}
Now the project itself requires this library. Here is the projects package.json
{
"name": "project",
"version": "1.0.0",
"description": "I am the project",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "Some Other Cool Guy <someoneelse#example.com>",
"license": "MIT",
"dependencies": {
"config-lib": "file:../lib"
}
}
(The config-lib library in this example was loaded from a local folder.)
The config-lib library requires me, in my project, to create a configuration file called config.json (BTW... name it something more specific to your library as to not collide with a local project configuration if they have one).
Here is an example config.json:
{
"key1": "value1",
"key2": "value2",
"key3": "value3"
}
Finally, in my project I can use the config-lib library to read my configuration file:
const configLib = require("config-lib");
(async () => {
console.log("Reading config");
const data = await configLib();
console.log("Here is my config: " + JSON.stringify(data));
console.log("key1 value: " + data.key1);
})();

Transform discord.js bot into exe

I have a working discord bot, but I would like to compile it into a .exe file. How to do that?
I tried to use pkg and nexe, but both did not make it correctly. Nexe did not even start giving me some strange errors that I did not manage to fix after reading docs and some discussions on the Internet.
Error: https://github.com/nexe/nexe/releases/download/v3.3.3/windows-x64-14.8.0 is not available, create it using the --build flag and Error: vcbuild.bat nosign release x64 exited with code: 1.
The pkg worked better, I got and exe file, but it did not seem to work:
I have this code, where bot is my discord client.
bot.on('ready', () =>
{
console.log(bot.guilds.cache.toJSON());
bot.guilds.cache.forEach((gui) =>
{
console.log(gui.id + ' ' + gui.name + ' ' + gui.memberCount);
});
console.log('Bot started!');
});
It gives one server when I start it using node index.js, but does not give any if I execute the exe file created, though the bot becomes online.
My package.json looks like this:
{
"name": "sth",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "node index.js"
},
"pkg": {
"assets": [ "jsons/**/*", "config.json" ]
},
"bin": "index.js",
"author": "",
"license": "ISC",
"dependencies": {
"discord.js": "^12.4.1"
}
}
What am I doing wrong? Why does the bot start, but does not seem to be able to do anything? What have I missed?
i don't know of an .exe file code you can use BUT you can use a .bat file and put it on desktop and create shortcuts or put it on shell:startup in that you will want to write this
#echo off
node "js file path"

Squirejs : requirejs is not defined

We have an amd/requirejs based web app. We came to a point to add a unit testing to our code. Googling returned that squireJs is best amd-require based mocking library. after installing, The problem is that we cant resolve the squirejs dependency. The issue seems so basic but we tried with both Mocha and Jasmine to use it, though it seems something we are forgetting to configure:
our js that we want to test looks basically like:
define(function employeeAndTagsPage(require) {
var global = require('common/global');
var customMessageWindow = require('../../customMessageWindow/customMessageWindow');
var currentTab;
var navigate = null;
// and other BL
});
Package.json:
{
"name": "jasmine.test",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "MIT",
"devDependencies": {
"amd-loader": "0.0.8",
"jasmine-node": "^3.0.0",
"requirejs": "^2.3.6",
"squirejs": "^0.2.1"
}
}
Jasmine_examples PlayerSpec.js:
describe("Player", function () {
require('amd-loader');
var Player = require('../../lib/jasmine_examples/Player');
var Song = require('../../lib/jasmine_examples/Song');
var requirejs = require('requirejs');
var squire = requirejs('squirejs'); // here it fails
var player, song, mock;
beforeEach(function() {
player = new Player();
song = new Song();
mock = new squire();
});
//unit tesitng
});
The error we are getting:
ReferenceError: requirejs is not defined
Stack:
at <Jasmine>
at getContext (c:\Synel\TESTS\eHarmonyNew-Jasmine\eHarmony\App\Test\node_modules\squirejs\src\Squire.js:58:5)
at Squire.configure (c:\Synel\TESTS\eHarmonyNew-Jasmine\eHarmony\App\Test\node_modules\squirejs\src\Squire.js:107:15)
The squirejs library code can be found here:
https://github.com/iammerrick/Squire.js/blob/master/src/Squire.js
What is the reason of the library being failed ? What we are forgetting? Any assist or reccomendation is appraciated

Azure Functions with node.js, Azure Service Bus and Apps Insight - Error on setup of AppsInsights

When I use azure module (to query Service Bus) and Application Insights module, I get the following error upon initialization of AppsInsight:
System.Exception : Error: Zone already loaded. at new Error (native) at Error.AppInsightsAsyncCorrelatedErrorWrapper
The code to replicate it is very simple:
var azure = require('azure');
var serviceBusService = azure.createServiceBusService(<Service Bus Endpoint>);
const appInsights = require("applicationinsights");
appInsights.setup(<Apps Insight key>).start();
The error is thrown on the last line and I assume is a result of dependencies overlapping between azure and applicationinsights module.
Any suggestions how to overcome this are appreciated!
According to your description, I created my JavaScript HttpTrigger function to check this issue. I used applicationinsights (version 0.22.0) and I could reproduce this issue as follows:
package.json:
{
"name": "functions-app-insights",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"applicationinsights": "^0.22.0",
"node-uuid": "^1.4.8"
}
}
Then I checked the applicationinsights package and call appInsights.setAutoDependencyCorrelation(false), then it could work as expected as follows:

Resources