npm bin param throwing an unexpected error - node.js

I'm trying to create an npm package called loca-mapper and for some reason it doesn't run when I include in my scripts: map: loca-mapper and launch npm run map, but it behaves correctly if you:
cd node_modules/loca-mapper
npm i (after all some dependencies won't be there due to the auto-resolve)
node ./index.js
What i get is an error message as follows:
/Users/{USER}/{PATH_TO_PROJECT}/node_modules/.bin/loca-mapper: line 1: syntax error near unexpected token `('
/Users/{USER}/{PATH_TO_PROJECT}/node_modules/.bin/loca-mapper: line 1: `const { getData } = require("./getLanguages/getLanguages.js");'
The content of my index.js is structured like this:
const { getData } = require("./getLanguages/getLanguages.js");
const { getConfig } = require("./utils/getConfig");
getData(getConfig());

Adding #!/usr/bin/env node at the beginning of the file would solve the issue.
#!/usr/bin/env node
const { getData } = require("./getLanguages/getLanguages.js");
const { getConfig } = require("./utils/getConfig");
getData(getConfig());

Related

No Response when calling FIDE-Ratings-Scraper NPM Package in JavaScript

I have used npm to install this package: https://github.com/xRuiAlves/fide-ratings-scraper using npm i fide-ratings-scraper. I use node to run a script with the following code in it:
var fideRatingsScraper = require("fide-ratings-scraper")
//Danii Dubov's FIDE player id: 24126055
console.log(fideRatingsScraper)
var fullInfo = fideRatingsScraper.getPlayerFullInfo('24126055');
console.log(fullInfo)
I get a response that shows that some code is executing. For the line where I print the variable fideRatingsScraper I get:
{
getPlayerFullInfo: [AsyncFunction: getPlayerFullInfo],
getPlayerElo: [AsyncFunction: getPlayerElo],
getPlayerHistory: [AsyncFunction: getPlayerHistory],
getPlayerRank: [AsyncFunction: getPlayerRank],
getPlayerPersonalData: [AsyncFunction: getPlayerPersonalData]
}
When I try to print out the variable fullInfo terminal prints out:
Promise { <pending> }
What am I missing here? I want to get the fullInfo for any player ID I list; I seem to be missing something simple.

Why am I getting Error: Configuration property “jwtPrivateKey” is not defined?

I keep getting this error message when I run my index.js file via NodeJS terminal. My editor is VS Code. I am on Windows.
I loaded npm config module into my index.js file. I created a custom-environment-variables.json. I set my password, vidlyPrivateKey, in my Node Terminal. I don't know why this is happening. Any help would be much appreciated!
Here is my index.js code:
const config = require('config');
try {
const myKey = config.get("jwtPrivateKey");
debug(myKey);
} catch (error) {
debug(error, "FATAL ERROR: jwtPrivateKey is not defined.");
return process.exit(1);
}
custom-environment-variables.json:
{
"jwtPrivateKey": "vidlyPrivateKey"
}
It is because the naming of the file, it should be inside a config folder and be name as default.json , config/default.json
These are the documentation https://www.npmjs.com/package/config.

Make node application executable in a NX workspace

I really like the structure of a NX workspace, and that lead me to start using it when building a new CLI project.
I started with creating a #nrwl/node:application but i currently is having some issues making it executable.
I believe this is not a problem with NX itself, but i can't add a shebang #!/usr/bin/env node in the main.ts file since the tsc transpiler will complain.
Module parse failed: Unexpected character '#' (1:0) File was processed
with these loaders: * ./node_modules/ts-loader/index.js
I have added the "bin": {"cli": "main.js"} property in my package.json file but if i run the main.js file without the shebang i will get this error:
line 1: syntax error near unexpected token `('
C:\Users\*\AppData\Roaming\npm/node_modules/*/dist/apps/*/main.js: line 1: `(function(e, a) { for(var i in a) e[i] = a[i]; }(exports, /******/ (function(modules) { // webpackBootstrap
Is there any smart way of solving this?
Steps to reproduce:
npx create-nx-workspace#latest cli-workspace --preset empty --cli nx --nx-cloud false
cd cli-workspace
npm install -D #nrwl/node
nx generate #nrwl/node:application my-cli
Add #!/usr/bin/env node to the top of the main.ts file
npm start
I've had the same problem. I could solve this by using the #nx-extend/gcp-functions:build builder to build the application, then I've created a custom executor to install the application as a CLI tool.
import { ExecutorContext } from '#nrwl/devkit';
import { exec } from 'child_process';
import { promisify } from 'util';
import * as fs from 'fs';
export interface NodeInstallOptions {
buildPath: string;
appName: string;
}
export default async function nodeInstallExecutor(
options: NodeInstallOptions,
context: ExecutorContext
) {
let success = true;
const mainPath = `${options.buildPath}/main.js`;
console.log('Building library...');
await runBashLine(success, `nx build ${options.appName}`);
console.log('Adding shebang line to main.js...');
const file = fs.readFileSync(mainPath, 'utf8');
const first_line = file.split("\n")[0];
if (first_line !== '#!/usr/bin/env node') {
var data = "#!/usr/bin/env node\n\n";
data += fs.readFileSync(mainPath, 'utf8');
fs.writeFileSync(mainPath, data);
}
console.log("Packing library...")
await runBashLine(success, `cd ${options.buildPath}; npm pack`);
console.log('Installing library...');
await runBashLine(success, `npm install -g ${options.buildPath}/*.tgz`);
return { success };
}
async function runBashLine(success: boolean, line: string) {
const { stdout, stderr } = await promisify(exec)(line);
console.log(stdout);
console.error(stderr);
success = success && !stderr;
}

Node TypeError - "not a function" on require()'d class method

I have the following class:
const exec = require('child_process').execSync;
class Git {
static branchExists (branchNameToCheck) {
return ( exec(`git rev-parse --verify --quiet ${branchNameToCheck} > /dev/null`).length > 0 );
}
}
module.export = Git;
This is called in the following (simplified) script:
#!/usr/bin/env node
const Git = require('./classes/Git');
if (Git.branchExists('develop')) console.log('success');
I get the following error:
Git.branchExists();
^
TypeError: Git.branchExists is not a function
Why is it not recognising branchExists as a function? When I run console.log(Git) I get {}.
I think it may just be a typo: module.export = Git; -> module.exports = Git;. If you don't define module.exports, the imported object ("Git" in this case) will be an empty object https://stackabuse.com/how-to-use-module-exports-in-node-js/

"ReactBingmaps" does not work with next - css file/module from node_modules is not supported

Code repo is here: "https://github.com/jim-king-2000/nextbugrepro".
Steps to reproduce the behavior, please provide code snippets or a repository:
Create a sample next project. (see next.js tutorial.)
npm i react-bingmaps
Add "import { ReactBingmaps } from 'react-bingmaps';" into "pages/index.js".
npm install --save #zeit/next-css
create next.config.js and copy the following code:
// next.config.js
const withCSS = require('#zeit/next-css')
module.exports = withCSS()
See the error:
./node_modules/react-bingmaps/lib/components/ReactBingmaps/ReactBingmaps.css 1:0
Module parse failed: Unexpected token (1:0)
You may need an appropriate loader to handle this file type.
.react-bingmaps{
| width: 100%;
| height: 100%
See this and this github issues.
As a temporary hack, try adding this to the top of your next.config.js file:
if (typeof require !== "undefined") {
require.extensions[".css"] = () => {};
}

Resources