I have one shell command which is working fine from terminal but when I try to run from nodejs it is giving me the error
Orignal Command
awk -v RS='"[^"]*"' '{n+=gsub(/\n/, "&")} END{print n}' <(sed '$s/$//' file.txt)
Node Js Code
execSync("awk -v RS='\"[^\"]*\"' '{n+=gsub(/\\n/, \"&\")} END{print n}' <(sed '$s/$//' "+ filePath+')')
The exesync is giving the same output but it is showing me the error Syntax error: "(" unexpected
<() is a bash-specific process substitution syntax. execSync defaults to using /bin/sh, usually a narrowly POSIX-compliant shell, which means it doesn't support the syntax. Explicitly use bash instead:
execSync("command goes here", {
shell: "/bin/bash"
});
Related
I have an index.js file that I want to load in the Node REPL to try some stuff, but when I use .load index.js in the REPL, it goes in an infinite loop and keeps repeating the first line in the file const mongoose = require('mongoose');. I found an alternative solution which works in Ubuntu 20.04.5 in WSL2, which is to use the command node -i -e "$(< index.js)" in the terminal which loads the file perfectly fine and I can interact with its contents. But when I try the same command in PowerShell it gives me this error:
< : The term '<' 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 line:1 char:15
+ node -i -e "$(< index.js)"
+ ~
+ CategoryInfo : ObjectNotFound: (<:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
C:\Program Files\nodejs\node.exe: -e requires an argument
The reason I'm asking about PowerShell "even though I use Ubuntu and things work there", is that I'm taking a web development course, and I provided the solution of using node -i -e "$(< index.js)" to people who were having the same issue, but other people can't get this to work in PowerShell, so I'm just trying to help. and I couldn't find any solution online to this .load issue, or to using the node -i -e "$(< index.js)" command in PowerShell.
index.js contents:
const mongoose = require('mongoose');
mongoose.set('strictQuery', false);
mongoose.connect('mongodb://localhost:27017/movieApp', { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => {
console.log("CONNECTION OPEN!!!")
})
.catch(err => {
console.log("OH NO ERROR!!!!")
console.log(err)
})
const movieSchema = new mongoose.Schema({
title: String,
year: Number,
score: Number,
rating: String
});
const Movie = mongoose.model('Movie', movieSchema);
const amadeus = new Movie({
title: 'Amadeus',
year: 1986,
score: 9.2,
rating: 'R'
});
In my experience $(...) on PowerShell acts strangely, and doesn't produce the expected result every time. Also < operator is not currently supported on Windows.
However, I managed to get the desired behaviour by using:
node -i -e echo "./index.js"
I am taking the same class. I haven't been able to get the .load index.js to work in PowerShell either -- even after updating node to the current version (v19) (rather than the LTS (v18)). But the command node -i -e "$(< index.js)" does seem to work properly if I change my VSCode terminal to gitBash (which apparently is what the course recommends, at least according to some posts from the TAs). But the command given in the lecture doesn't seem to work in any terminal shell.
Running this command using spawnSync use to work before I added in npx.
spawnSync(`npx git add-coauthor ${commandKey} "${name}" ${email}`)
Now I get an error from the git-mob cli saying Incorrect Number of Parameters. It sees four instead of three after add-coauthor it seems like it's ignoring the double quotes around name.
Error: "Incorrect Number of Parameters [ 'zsgi', 'first', 'lastname', 'someone#email.com' ]\n"
Things I've tried but I get the same error:
spawnSync(
"npx",
["git", "add-coauthor", commandKey, `"${name}"`, email]
);
spawnSync(
`npx git add-coauthor "${commandKey} \"${name}\" ${email}"`
);
If I run Git Mob cli command directly in the terminal this works:
npx git add-coauthor "jsj \"alsk la\" sls#al.com"
Grateful for any suggestions.
The code can be found here.
Edits: More info
This could be related to Windows 10 cmd as it seems to work fine on Mac OS.
Node version: 12.11.0
Npm version: 6.11.3
I am trying to publish npm package, when i am install the package globally and try to run the cli command i get this errors:
/.nvm/versions/node/v0.12.2/bin/myPack: line 1: use strict: command not found
/.nvm/versions/node/v0.12.2/bin/myPack: line 3: syntax error near unexpected token `('
/.nvm/versions/node/v0.12.2/bin/myPack: line 3: `var _commandLineArgs = require('command-line-args');'
The top of the file that the error refer to:
'use strict';
var _commandLineArgs = require('command-line-args');
var _commandLineArgs2 = _interopRequireDefault(_commandLineArgs);
The package.json bin section:
"bin": {
"myPack": "dist/myPack.js"
}
When i am running this in my local development this works well, what is the problem?
Your script should start with a shebang line, otherwise it will be executed as a shell script (hence the errors).
Add this as first line to dist/myPack.js:
#!/usr/bin/env node
I'm facing an issue while trying to get javascript unit tests to work at the command line using qunit.
Here's some sample code to reproduce the error:
file util.js:
function abc() {
return 'abc';
}
if (typeof module !== 'undefined' && module.exports) {
module.exports = {
abc: abc
};
}
file util-tests.js
var qunit = require("qunit");
test("Test abc function", function () {
equal(util.abc(), 'abc');
});
With these files, I can run tests using the following command (gives a table-like output in the shell with the test results):
qunit -c util:util.js -t util-tests.js
Now it breaks if I add the following to util.js
$(document).ready(function () {
/* some code here */
});
Here's the error output:
qunit -c util:util.js -t util-tests.js
Testing /home/mfrere/jstst/util.js ... [Error: Uncaught exception in child process.]
same problem with:
var a = $;
or:
var a = document;
So this makes me think that I need to import jQuery somehow, so I thought about adding jquery.js as a dependency to the command, like this:
qunit -c util:util.js -t util-tests.js -d jquery.js
The above command gives me the same 'Uncaught exception' error, even if util.js doesn't contain any reference to '$'.
I'll probably need to do something else to get qunit to recognize 'document' as well, but I don't know what or how.
Now here's my question: what should I do to get this to work? It is important to keep in mind I want to test my files at the command line, not in a browser.
Just in case I did something wrong in the setup process, this is how I installed node/qunit (under ubuntu):
git clone git://github.com/creationix/nvm.git ~/.nvm
in .bashrc, I added the following line:
source ~/.nvm/nvm.sh
picked a specific version of node
nvm install v0.9.2
nvm alias default 0.9
and installed qunit
npm install -g qunit
finally I had to add this in .bashrc as well:
export NODE_PATH=~/.nvm/v0.9.2/lib/node_modules
You haven't imported jQuery:
$ = require('jquery'),
jQuery = require('jquery');
If you're using browserify, change that to 'jquery-browserify'.
Are there equivalent to perl -c syntax check for JavaScript from command? Given that I have NodeJS installed?
JSLint is not considered as it is not a real parser. I think YUI compressor is possible but I don't want to install Java on production machines, so I am checking if Node.JS already provided this syntax check mechanism.
If you want to perform a syntax check like that way we do in perl ( another scripting language) you can simply use node -c <js file-name>
e.g. a JS file as test.js has:
let x = 30
if ( x == 30 ) {
console.log("hello");
else {
console.log( "world");
}
now type in node -c test.js
it will show you
test.js:5
else {
^^^^
SyntaxError: Unexpected token else
at startup (bootstrap_node.js:144:11)
at bootstrap_node.js:509:3
Now after fixing the syntax issue as
let x = 30
if ( x == 30 ) {
console.log("hello");
} else {
console.log( "world");
}
check syntax - node -c test.js will show no syntax error!!
Note - we can even use it to check syntax for all files in a dir. - node -c *.js
Try uglify. You can install it via npm.
Edit: The package name has changed. It is uglify-js.
nodejs --help
explains the -p switch: it evaluates the supplied code and prints the results. So using nodejs -p < /path/to/file.js would be a disastrous way to check the validity of node.js code on your server. One possible solution is the one indicated in this SO thread. The one thing not so good about it - the syntax error messages it reports are not terribly helpful. For instance, it tell you something is wrong but without telling you where it is wrong.