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

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.

Related

Stream module error when using Browserify

Problem
When trying to build my bundle.js file, I get the following:
Error: Can't walk dependency graph: ENOENT: no such file or directory, lstat 'C:\[filepath&filename]\stream'
required by C:\[filepath]\script.js
My package.json file is as follows:
{
"name": "[projectName]",
"version": "1.0.0",
"description": "",
"main": "script.js",
"scripts": {
"build": "browserify script.js -o bundle.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"devDependencies": {
"browserify": "^17.0.0",
"crypto-js": "^4.1.1",
"stream-consumers": "^1.0.2"
}
}
High level, the code I'm trying to run is as follows:
var CryptoJS = require('crypto-js');
const { json } = require('stream/consumers');
function doSomething() {
}
doSomething();
What I've tried
I've tried a number of different recommended ways to fix this, including:
Adding './' - as recommended here which gives 'Cannot find module'
Deleting package-lock.json file and then installing the packages I wanted to install - as recommended here
This unblocked the issue for me.
It turned out that:
const { json } = require('stream/consumers');
wasn't required, so when I commented it out, it seemed to resolve the issue...

Mocha and Import Syntax: Cannot find module

Maintainer of multiple npm packages here. Been using mocha with the require syntax and wanting to migrate to the import syntax.
The error I am getting is
Cannot find module '<project>/src/index' imported from <project>/test/index.spec.js
Steps to Reproduce
With the following three files
src/index.js
export const sum = (a, b) => a + b;
test/index.spec.js
import { sum } from '../src/index';
const expect = require('chai').expect;
describe('Testing Index', () => {
it('Testing sum', () => {
expect(sum(7, 13)).to.equal(20);
});
});
package.json
{
"name": "mocha-debug",
"type": "module",
"main": "index.js",
"scripts": {
"test": "mocha \"./test/**/*.spec.js\""
},
"license": "ISC",
"devDependencies": {
"chai": "4.3.4",
"mocha": "9.1.4"
}
}
and using node v14.18.2, run yarn install and
yarn test
> `Cannot find module '<project>/src/index' imported from <project>/test/index.spec.js`
Notes
I've found a related issue that recommends using babel with --require #babel/register, but wasn't able to get over the error.
I've set up a test repo to make it easy to reproduce the issue
https://github.com/simlu/mocha-debug
Question
What am I doing wrong here? How do I get the tests to run successfully?
I solved it by just adding the file extension in my case I was importing my mongodb model so I imported with the file extension .ts
var Employee = require('../models/Employee.ts')
Which solved the issue

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

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...

'ReferenceError: jest is not defined' when running unit test

I'm in the early stages of a new app that so far just uses vanilla JS. I'm trying to use ES6 modules for my Jest unit tests, so I followed the 2020 updated instructions on making this possible.
However, after following those instructions, I get the error ReferenceError: jest is not defined when running my unit test.
Here's my package.json:
{
"version": "1.0.0",
"main": "app.js",
"type": "module",
"jest": {
"testEnvironment": "jest-environment-node",
"transform": {}
},
"scripts": {
"test": "node --experimental-vm-modules node_modules/jest/bin/jest.js",
"start": "node server.js"
},
"license": "ISC",
"devDependencies": {
"express": "^4.17.1",
"jest": "^26.6.3",
"jest-environment-node": "^26.6.2",
"open": "^7.3.0"
},
"dependencies": {}
}
Below is my test file. The error occurs due to the jest.fn call:
import { getTotalNumPeople } from "./app.js";
test("Get total number of people", async () => {
global.fetch = jest.fn(() => Promise.resolve({
json: () => Promise.resolve({count: 15})
})
)
expect(await getTotalNumPeople()).toBe(15);
});
Any ideas on why this is happening? I'm confident that the issue has to do with the steps I followed to support ES6 modules. Prior to these changes, my test ran fine when I simply pasted the getTotalNumPeople function in my test file.
If I comment out mocking my function, I then get a ReferenceError about fetch not being defined (since getTotalNumPeople uses fetch). So it's not just jest that's not defined.
I notice that if I do not specify jest-environment-node as my test environment, the error changes to ReferenceError: global is not defined due to referring to global.fetch in my test. Just thought I'd note that in case that helps.
It looks like you didn’t import jest, so you have to just add this line to the top of the file:
import {jest} from '#jest/globals'
For more details, see this issue on native support for ES6 modules in Jest.
while essentially the same as the answer of Rupesh - you can expose jest globally without having to import it in each test file - by adding a setup-file to the jest configuration:
"jest": {
"setupFiles": [
"<rootDir>/test-setup.js"
]
}
then add this to test-setup.js:
import { jest } from '#jest/globals';
global.jest = jest;
also in general ESM support for jest is improved by a test script in package.json as so:
"scripts": {
"test": "node --no-warnings --experimental-vm-modules $( [ -f ./node_modules/.bin/jest ] && echo ./node_modules/.bin/jest || which jest )"
},

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

Categories