"The term '/node.exe' is not recognized as the name of a cmdlet, function, script file, or operable program" - javascript

I'm attempting to make a CLI with Node.js following the tutorial on Twilio and after doing npm link I get this error when using the command. I read an old overflow post which said to add node to my environment variables, which I have.
Here's the error:
& : The term '/node.exe' is not recognized as the name of a cmdlet, function, script file, or operable program. Check
the spelling of the name, or if a path was included, verify that the path is correct and try again.
At C:\Users\thedi\AppData\Roaming\npm\create-project.ps1:15 char:5
+ & "/node$exe" "$basedir/node_modules/#thedigs/create-project/bin/c ...
+ ~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (/node.exe:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
And here's my current code:
// bin/create-project
#!/usr/bin/env/node
require = require('esm')(module /*, options */);
require('../src/cli').cli(process.argv);
// src/cli.js
export function cli(args) {
console.log(args);
}
// package.json
{
"name": "#thedigs/create-project",
"version": "1.0.0",
"description": "A CLI to bootstrap my new projects, whatever that means.",
"main": "src/index.js",
"scripts": {
"start": "nodemon ."
},
"publishConfig": {
"access": "public"
},
"bin": {
"#thedigs/create-project": "bin/create-project",
"create-project": "bin/create-project"
},
"keywords": [
"cli",
"create-project"
],
"author": "thedigs",
"license": "ISC",
"dependencies": {
"#types/node": "^14.14.31",
"esm": "^3.2.25",
"nodemon": "^2.0.7"
}
}
My best guess is the tutorial is behind versions, hopefully one of you can sort this out for me. Thanks!
Environment Variables

I was also looking for the answer but after comparing this code and my code suddenly realized that the path #!/usr/bin/env/node given to bin/create-project is completely wrong.
In my case, I have given it as #! /user/bin/env node but it has to be usr instead of using user.
In this case, it has to be...
File: bin/create-project
#! /usr/bin/env node
require = require('esm')(module /*, options */);
require('../src/cli').cli(process.argv);
Those spaces are a must when it comes to path.

For reference: first line is a so-called shebang.
And why to use env here and not call node directly, is summarized here in another SE post.
Short: env acts as a proxy to find your desired interpreter, in your case node on the target system, even if it is maybe found in the users ~ home dir or something...

Related

Cannot get #vercel/ncc working throws Module not found error

I have been trying to get the following tutorial working for building custom github actions https://docs.github.com/en/actions/creating-actions/creating-a-javascript-action. The article states that if you don't want to check in your node_modules folder to use #vercel/ncc package to compile your code into a single file. I have tried the NCC sample here https://github.com/vercel/ncc/tree/main/examples/hello-world but I get the same error no matter what I do. The error I get is this:
Error: Cannot find module 'C:\Projects\github-runner-test\.github\actions\read-deploy-instructions\index.js'
Require stack:
- C:\Projects\github-runner-test\.github\actions\read-deploy-instructions\node_modules\#vercel\ncc\dist\ncc\cli.js
at Function.Module._resolveFilename (node:internal/modules/cjs/loader:933:15)
at resolve (node:internal/modules/cjs/helpers:108:19)
at runCmd (C:\Projects\github-runner-test\.github\actions\read-deploy-instructions\node_modules\#vercel\ncc\dist\ncc/cli.js.cache.js:1:52001)
at Object.819 (C:\Projects\github-runner-test\.github\actions\read-deploy-instructions\node_modules\#vercel\ncc\dist\ncc/cli.js.cache.js:1:48838)
at __webpack_require__ (C:\Projects\github-runner-test\.github\actions\read-deploy-instructions\node_modules\#vercel\ncc\dist\ncc/cli.js.cache.js:1:59074)
at C:\Projects\github-runner-test\.github\actions\read-deploy-instructions\node_modules\#vercel\ncc\dist\ncc/cli.js.cache.js:1:59286
at C:\Projects\github-runner-test\.github\actions\read-deploy-instructions\node_modules\#vercel\ncc\dist\ncc/cli.js.cache.js:1:59347
at Object.<anonymous> (C:\Projects\github-runner-test\.github\actions\read-deploy-instructions\node_modules\#vercel\ncc\dist\ncc\cli.js:8:28)
at Module._compile (node:internal/modules/cjs/loader:1105:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1159:10) {
code: 'MODULE_NOT_FOUND',
requireStack: [
'C:\\Projects\\github-runner-test\\.github\\actions\\read-deploy-instructions\\node_modules\\#vercel\\ncc\\dist\\ncc\\cli.js'
]
}
I am running latest Node on Windows 10 with latest GIT and cannot get this to work at all. I have tried bash, powershell, moved directories around and nothing seems to work. Below is my project structure:
My package.json looks like this:
{
"name": "read-deploy-instructions",
"version": "1.0.0",
"description": "",
"main": "index.js",
"type": "module",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "ncc build index.js -o /dist"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"#actions/core": "^1.9.0",
"#actions/github": "^5.0.3"
},
"devDependencies": {
"#vercel/ncc": "latest"
}
}
My index.js looks like this:
import core from '#actions/core';
import github from '#actions/github';
try {
// `who-to-greet` input defined in action metadata file
const nameToGreet = core.getInput('who-to-greet');
console.log(`Hello ${nameToGreet}!`);
const time = (new Date()).toTimeString();
core.setOutput("time", time);
// Get the JSON webhook payload for the event that triggered the workflow
const payload = JSON.stringify(github.context.payload, undefined, 2)
console.log(`The event payload: ${payload}`);
} catch (error) {
core.setFailed(error.message);
}
If I run the command:
npm run build
I get the error shown above. I have seen multiple people posting it doesn't work with similar errors but no resolution. Does anyone have any ideas?
Thanks in advance,
OK after many a wasted hour I realized the file I was trying to target was named incorrectly. I was telling the NCC commands to look for "index.js" but had mistakenly named it "index,js". After renaming the file the NCC commands worked successfully and as expected.

how can I use top level "await" in typescript next.js

When I use "await" on top-level like this:
const LuckyDrawInstance=await new web3.eth.Contract(abi)
I got a warning on the terminal: "set experiments.topLevelAwait true". When I tried to add this to "tsconfig.json", it still does not work. it says "experiments" property does not exist.
I could wrap it inside an async function but I want to set it without a wrapped function.
It is nothing to do with the tsconfig.json. You have to set it inside next.config.js. New version of next.js uses webpack5 and webpack5 supports top level await.
module.exports = {
webpack: (config) => {
// this will override the experiments
config.experiments = { ...config.experiments, topLevelAwait: true };
// this will just update topLevelAwait property of config.experiments
// config.experiments.topLevelAwait = true
return config;
},
};
NOTE
You have to use it outside the functional component:
export default function Navbar() {
// this will throw error
// Syntax error: Unexpected reserved word 'await'.
const provider=await customFunction()
return (
<section>
</section>
);
}
Warning
Since it is experimental, it might be broken in some versions
The latest solution as of writing this post that worked for me is using Babel instead of SWC since Next.js does not allow custom SWC configuration, therefore, you cannot allow topLevelAwait through .swcrc file.
Add Babel plugin called #babel/plugin-syntax-top-level-await into your package.json.
eg.
{
"devDependencies": {
"#babel/plugin-syntax-top-level-await": "^7.14.5"
}
}
Create .babelrc file in the root directory of your project where package.json lives.
Inside .babelrc make sure to include next/babel preset and the topLevelAwait plugin.
eg.
{
"presets": ["next/babel"],
"plugins": [
"#babel/plugin-syntax-top-level-await"
]
}
This is the easiest solution until Next.js team allows us to include SWC configuration. Note that by doing this you will not have SWC performance benefit since it will be disabled in favor of Babel.
I have been struggling with this for 2-3 days. Here is a solution that works. Please follow the following steps.
1. Copy paste the following in your package.json
{
"name": "projectname",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "mocha",
"dev": "next dev"
},
"author": "",
"license": "ISC",
"dependencies": {
"#truffle/hdwallet-provider": "^2.0.1",
"fs-extra": "^10.0.0",
"ganache-cli": "^6.12.2",
"mocha": "^9.1.4",
"next": "^12.0.8",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"solc": "^0.8.9",
"web3": "^1.7.0",
"#babel/plugin-syntax-top-level-await": "^7.14.5"
},
"devDependencies": {
"#babel/plugin-syntax-top-level-await": "^7.14.5"
}
}
2. Delete your node_modules folder
3. Goto your project's root directory and reinstall all the packages using npm install command
4. Create a new file in your project's root directory and call it "next.config.js"
5. Copy paste following code in next.config.js file and save.
module.exports = {
// target: 'experimental-serverless-trace',
webpack: (config) => {
config.experiments = config.experiments || {};
config.experiments.topLevelAwait = true;
return config;
},
};

Unexpected token 'export' while importing dynamically a js file

I am creating a script that would run over certain js files in my system (outside my project, actually they are plain js files in a React application) and I want to evaluate the content of them and get the content of the variables to use them in my script. See the code here:
import glob from 'glob';
const cwd = '/path/to/code';
const findAll = () => glob('**/*config.js', { cwd }, (err, matches) => {
// matches is an array of paths like ['dir/myfile-config.js']
if (err) {
console.error(err);
return;
}
const file = matches[0];
// file here is the path to a JS file that contains something like export const CONFIG = {prop1: 'value1'};
import(`${cwd}/${file}`)
.then(console.log)
.catch(console.error);
});
When I invoke the import() function it complains about:
export const CONFIG = {
^^^^^^
SyntaxError: Unexpected token 'export'
However it is importing correctly 'glob' library. I don't understand why it cannot import that file and could not find any info in the internet about it. I could find info about how to make node understand the module system but this is not the problem here as my program understands import/export sintaxis.
I am running my program with node 12.13.0 running the file like:
node --experimental-modules ./index.js
I also tried with node 13.14.0 (removing the --experimental-modules flag) and got the same result :(
Any help would be really appreciated.
I add also the package.json I am using:
{
"name": "config-retriever",
"version": "1.0.0",
"description": "",
"main": "index.js",
"license": "MIT",
"type": "module",
"private": true,
"dependencies": {
"glob": "^7.1.6"
}
}
The problem is that by default, Node.js determines whether something is a CJS module or an ESM module by using its closes package.json. You've said that these configs are outside the project, so there's no package.json to tell Node.js to treat them as ESM rather than CJS.
Options:
Add a package.json to the place where the configs are located that has "type": "module" in it. Literally just this does it:
{
"type": "module"
}
You can force that by giving the config files the extension .mjs, which is always treated as an ESM module (and changing your glob call accordingly). For me that's not a great solution, but...
It also may be possible to use the getFormat hook to tell Node that these config files are ESM, not CJS. However, a note on it says that it's in the process of being redesigned and that you shouldn't rely on it.
If you want to run a particular function in a js file, you should use Make-Runnable module.
Put this code snippet at the end of your js file.
require('make-runnable/custom')({
// printOutputFrame: false
});

How do I execute different Testcases with different structure through NodeJS and Mocha

How do I execute different Testcases with different structure through NodeJS and Mocha.
Moving forward I intend to integrate Selenium + NodeJS + Mocha
I have just started to explore NodeJS with Mocha and need some help.
Installed node.js:
C:\Users\AtechM_03>node -v
v6.11.2
Installed npm:
C:\Users\AtechM_03>npm -v
3.10.10
Configured nodeclipse as per this link and my Project structure looks like:
Installed Mocha at the default location (through command-line) as per this link.
C:\Users\AtechM_03>npm install -g mocha
C:\Users\AtechM_03\AppData\Roaming\npm\mocha -> C:\Users\AtechM_03\AppData\Roaming\npnode_modules\mocha\bin\mocha
C:\Users\AtechM_03\AppData\Roaming\npm\_mocha -> C:\Users\AtechM_03\AppData\Roaming\n\node_modules\mocha\bin\_mocha
C:\Users\AtechM_03\AppData\Roaming\npm
`-- mocha#3.5.3
Followed this link to write a program in NodeJS integrating Mocha.
Created a directory named test with in NodeProject space.
Within test folder created a file named test.js
Executed npm init to interactively create a package.json file.
C:\Users\AtechM_03>cd C:\Users\AtechM_03\LearnAutmation\NodeProject
C:\Users\AtechM_03\LearnAutmation\NodeProject>npm init
This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.
See `npm help json` for definitive documentation on these fields
and exactly what they do.
Use `npm install <pkg> --save` afterwards to install a package and
save it as a dependency in the package.json file.
Press ^C at any time to quit.
name: (NodeProject) test
version: (1.0.0) 1.0.0
description: test123
entry point: (index.js) test.js
test command: (mocha) mocha
git repository:
keywords:
author: debanjan
license: (ISC)
About to write to C:\Users\AtechM_03\LearnAutmation\NodeProject\package.json:
{
"name": "test",
"version": "1.0.0",
"description": "test123",
"main": "test.js",
"directories": {
"test": "test"
},
"dependencies": {
"g": "^2.0.1",
"selenium-webdriver": "^3.5.0"
},
"devDependencies": {
"mocha": "^3.5.3"
},
"scripts": {
"test": "mocha"
},
"author": "debanjan",
"license": "ISC"
}
Is this ok? (yes)
C:\Users\AtechM_03\LearnAutmation\NodeProject>
package.json got generated within the Project Scope i.e. under C:\Users\AtechM_03\LearnAutmation\NodeProject as follows:
{
"name": "test",
"version": "1.0.0",
"description": "test123",
"main": "test.js",
"directories": {
"test": "test"
},
"dependencies": {
"g": "^2.0.1",
"selenium-webdriver": "^3.5.0"
},
"devDependencies": {
"mocha": "^3.5.3"
},
"scripts": {
"test": "mocha"
},
"author": "debanjan",
"license": "ISC"
}
Added code to test.js as follows:
// Require the built in 'assertion' library
var assert = require('assert');
// Create a group of tests about Arrays
describe('Array', function() {
// Within our Array group, Create a group of tests for indexOf
describe('#indexOf()', function() {
// A string explanation of what we're testing
it('should return -1 when the value is not present', function(){
// Our actual test: -1 should equal indexOf(...)
assert.equal(-1, [1,2,3].indexOf(4));
});
});
//Create a test suite (group) called Math
describe('Math', function() {
// Test One: A string explanation of what we're testing
it('should test if 3*3 = 9', function(){
// Our actual test: 3*3 SHOULD EQUAL 9
assert.equal(9, 3*3);
});
// Test Two: A string explanation of what we're testing
it('should test if (3-4)*8 = -8', function(){
// Our actual test: (3-4)*8 SHOULD EQUAL -8
assert.equal(-8, (3-4)*8);
});
});
});
Executed npm test from project space which runs successfully:
C:\Users\AtechM_03\LearnAutmation\NodeProject>npm test
> temperature#1.0.0 test C:\Users\AtechM_03\LearnAutmation\NodeProject
> mocha
Array
#indexOf()
v should return -1 when the value is not present
Math
v should test if 3*3 = 9
v should test if (3-4)*8 = -8
3 passing (18ms)
Followed this link to write a second program in NodeJS integrating Mocha.
Created a separate directory named temperature with in NodeProject space.
In the temperature directory created a file named app.js and a folder name test
Within the test folder, created a file named test.js
Moved the previous package.json to a sub-directory and executed npm init to interactively create a new package.json file again.
C:\Users\AtechM_03>cd C:\Users\AtechM_03\LearnAutmation\NodeProject
C:\Users\AtechM_03\LearnAutmation\NodeProject>npm init
This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.
See `npm help json` for definitive documentation on these fields
and exactly what they do.
Use `npm install <pkg> --save` afterwards to install a package and
save it as a dependency in the package.json file.
Press ^C at any time to quit.
name: (NodeProject) temperature
version: (1.0.0) 1.0.0
description: temp
entry point: (index.js) app.js
test command: (mocha) mocha
git repository:
keywords:
author: debanjanb
license: (ISC)
About to write to C:\Users\AtechM_03\LearnAutmation\NodeProject\package.json:
{
"name": "temperature",
"version": "1.0.0",
"description": "temp",
"main": "app.js",
"directories": {
"test": "test"
},
"dependencies": {
"g": "^2.0.1",
"selenium-webdriver": "^3.5.0"
},
"devDependencies": {
"mocha": "^3.5.3"
},
"scripts": {
"test": "mocha"
},
"author": "debanjanb",
"license": "ISC"
}
Is this ok? (yes)
New package.json gets created as follows:
{
"name": "temperature",
"version": "1.0.0",
"description": "temp",
"main": "app.js",
"directories": {
"test": "test"
},
"dependencies": {
"g": "^2.0.1",
"selenium-webdriver": "^3.5.0"
},
"devDependencies": {
"mocha": "^3.5.3"
},
"scripts": {
"test": "mocha"
},
"author": "debanjanb",
"license": "ISC"
}
The current temperature Testcase looks like:
Tried to execute this second program through npm test from the Project space but it still executes the first program as follows:
C:\Users\AtechM_03\LearnAutmation\NodeProject>npm test
> temperature#1.0.0 test C:\Users\AtechM_03\LearnAutmation\NodeProject
> mocha
Array
#indexOf()
v should return -1 when the value is not present
Math
v should test if 3*3 = 9
v should test if (3-4)*8 = -8
3 passing (18ms)
Question :
I know my second program app.js is incomplete and executing it will show error (e.g. 0 passing (20ms)) but my app.js is not getting invoked at all.
Can someone please guide/suggest me what I am doing wrong here?
Any suggestion/guide/pointer will be helpful.
Update:
As of now my current code for app.js is incomplete and contains the following code:
cToF = function(celsius) {
if(!Number.isInteger(celsius)) return undefined;
return celsius * 9 / 5 + 32;
}
fToC = function(fahrenheit) {
if(!Number.isInteger(fahrenheit)) return undefined;
return (fahrenheit - 32) * 5 / 9;
}
As per this website I am following I expect an error as 0 passing (20ms)
You've got quite the long description but the thing I extracted from it is that you have essentially a structure like this:
NodeProject
├── temperature
│   └── test
└── test
Then you go into NodeProject and run Mocha. By default Mocha will look only for test in the same directory where it is invoked. So it won't look for temperature/test. If you want Mocha to run the tests in temperature/test you have to tell Mocha explicitly. For instance, this would work:
mocha test temperature/test
I'll address a common misconception here because I often see people make the mistake: merely using the --recursive flag is not enough. If you use this flag, then after Mocha has identified directories in which to find tests, it will look in them recursively. However, it does not change how Mocha identifies directories in which to find tests. Specifically, if you use mocha --recursive, it will still only look in test, and it will look in subdirectories of test. This won't make it look in temperature/test. If you do have subdirectories in test and temperature/test, you could do:
mocha --recursive test temperature/test

Electron app name doesn't change

i'm packaging my application using electron-packager but isn't changing its name, and still display "Electron".
it's supposed to use the productName in my package.json but it doesn't change.
even if i made an installer, the name of the app installed, shortcut and process still is Electron
i've read that maybe the problem is electron-prebuilt but i didn't have it as a dependency on my project.
Any idea what is wrong?
Edit:
reading more on the documentation of electron-packager there's an options especially to windows. but when i use them throws me an error:
Fatal error: Unable to commit changes
undefined
the first time i used them was "working" good packaging my app, but still displaying wrong the appname
electron-packager ./ --platform=win32 --arch=ia32 --overwrite=true --appname="TierraDesktop" --version-string.ProductName="TierraDesktop" --version-string=InternalName="TierraDesktop" --version-string.CompanyName="Cosmica" --version-string.FileDescription="Sistema de gestion comercial" --version-string.OriginalFilename="TierraDesktop"
before was working with --version-string.ProductName but now even with it still throws that error.
here i'll leave you my packager.json that's on the root of my project
{
"name": "TierraDesktop",
"productName": "TierraDesktop",
"version": "2.0.5",
"description": "Aplicacion de escritorio tierra de colores",
"main": "main.js",
"scripts": {
"start": "electron main.js"
},
"repository": {
"type": "git",
"url": "git+https://github.com/xxxx/xxxxx.git"
},
"author": "xxxxx",
"devDependencies": {
"debug-menu": "^0.4.0",
"electron-winstaller": "^2.3.3"
},
"dependencies": {
"electron-json-storage": "^2.0.0"
}
}
Ok after trying and researching i've decided to package my application via programmatic API
with this script i can achieve all what i want. hope this help someone with the same problem.
var packager = require('electron-packager');
var options = {
'arch': 'ia32',
'platform': 'win32',
'dir': './',
'app-copyright': 'Paulo Galdo',
'app-version': '2.0.5',
'asar': true,
'icon': './app.ico',
'name': 'TierraDesktop',
'ignore': ['./releases', './.git'],
'out': './releases',
'overwrite': true,
'prune': true,
'version': '1.3.2',
'version-string':{
'CompanyName': 'Paulo Galdo',
'FileDescription': 'Tierra de colores', /*This is what display windows on task manager, shortcut and process*/
'OriginalFilename': 'TierraDesktop',
'ProductName': 'Tierra de colores',
'InternalName': 'TierraDesktop'
}
};
packager(options, function done_callback(err, appPaths) {
console.log(err);
console.log(appPaths);
});
electron-packager <sourcedir> <appname> --platform=<platform> --arch=<arch> [optional flags...]
If appname is omitted, this will use the name specified by
"productName" or "name" in the nearest package.json.
Have you tried to set the 'name' property in package.json?
#Paulo Galdo Sandoval's answer is correct for electron-packager, but as of version 9.0.0 of the package, it automatically grabs information for those fields (version-string is now win32metadata). See the release notes for that package
electron-packager checks the output directory for an existing package based on the version name. If you did not change the version name when you tried to re-package with a different product name, electron-packager probably told you in the console that it was skipping the packaging process because a package already exists.

Categories