The token '&&' is not a valid statement separator in this version - javascript

On the way of installing Webpack on my React Project, the following problem hinders my progress:
last step to configure the Webpack
npm run build && node ./dist/main.js
Error on Windows Power Shell / on Visual Studio Code
PS C:\Users\pythonbuddha\Desktop\to_experiment\to-do-list> npm run build && node ./dist/main.js
At line:1 char:15
+ npm run build && node ./dist/main.js
+ ~~
The token '&&' is not a valid statement separator in this version.
+ CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : InvalidEndOfLine
Tutorial which promised to configure the webpack
https://developerhandbook.com/webpack/webpack-4-from-absolute-scratch/
https://developerhandbook.com/webpack/how-to-configure-scss-modules-for-webpack/

It's because you're in PowerShell, try running it in CMD or Git Bash
Alternatively (if you wish to continue in PS):
(npm run build) -and (node ./dist/main.js)
3rd Alternative, just run them separetly,

I found that within PowerShell as my terminal within VS Code, replacing && in the command with ; did the trick.

PowerShell (Core) v7+ - but not Windows PowerShell - now does support && and ||, the pipeline-chain operators, so your command should work as-is there - see this answer for PowerShell-specific considerations for their use; see below for Windows PowerShell workarounds.
Conceptual note:
In all shells that support it (notably cmd.exe and POSIX-compatible shells such as Bash), && conditionally sequences commands: it executes its RHS command only if the LHS command indicated success; || is the inverse: it executes the RHS only if the LHS indicated failure.
This is important for preventing execution when it makes no sense to do so; e.g., in npm run build && node ./dist/main.js it only makes sense to run what was just built (with node) if the build succeeded, which is what && ensures.
Windows PowerShell workarounds:
The most succinct workaround:
npm run build; if ($?) { node ./dist/main.js }
This builds on the automatic $? variable, which is a Boolean indicating whether the most recent command succeeded.
The most robust workaround, needed if the commands use 2> redirections:
npm run build; if ($LASTEXITCODE -eq 0) { node ./dist/main.js }
Basing the success test on the automatic $LastExitCode variable, which reflects the process exit code of the most recently executed external program, avoids problems in Windows PowerShell[1] where the presence of stderr output in combination with redirecting it via 2> mistakenly sets $? to $false even when the process exit code is 0.
[1] The problems with 2> redirections are summarized in this answer. They also plague PowerShell (Core) up to version 7.1

The && operator is used in linux bash to run both commands after each other. (Also if the first command fails, the second won't be executed)
This does not work in PowerShell on Windows so just split both commands and run them separately:
npm run build
node ./dist/main.js
For completeness, Powershell can behave the same when you do (command1) -and (command2) and && might actually work depending on your PowerShell version.
See this for further info: https://stackoverflow.com/a/564092/2232127

I have solved the issue by upgrading powershell and renamed dir. path folder name by removing spaces. Now it works properly.
Powershell upgradation link
https://github.com/PowerShell/PowerShell/releases/tag/v7.2.0-preview.8

Since some people might arrive here in the same manner as I did, wondering why PowerShell would not allow me to perform a conditional AND operator between two variables within an if statement.
I solved it by evaluating the Left Condition with an If condition, and then the Right Condition immediately within the first true condition.
Example that produced the error:
$Path = "C:\\Temp\test"
$RootPath = "C:\\Temp"
$currentChildren = Get-ChildItem -Force -LiteralPath $Path
$isEmpty = $currentChildren -eq null
if ($isEmpty && $Path -ne $RootPath) {
Remove-Item -Force -LiteralPath $Path
}
$foo = "question"
$bar = "answer"
Example that I used to solve the problem:
$Path = "C:\\Temp\test"
$RootPath = "C:\\Temp"
$currentChildren = Get-ChildItem -Force -LiteralPath $Path
$isEmpty = $currentChildren -eq null
if ($isEmpty) {
if ($Path -ne $RootPath) {
Remove-Item -Force -LiteralPath $Path
}
}

Related

How to concat multiple bash commands?

Having this bash_profile commands, trying to run backend and frontend server in one single alias command i.e ins
alias is='ivui && npm run start:backend'
alias ib='ivbe && npm run start:dev'
alias ins='ib && is'
is referring to a different project folder and it starts the server and ib is also referring to a different folder and server. Trying to concat both, but the first one only triggers and concat of && is not executed.
Concat npm helps in combining both servers from single project folder, but wondering how we can get this done using bash_profile? so that by executing just ins, it must start backend server first and frontend also.
The reason your double alias command (ib && is) does not work is because, as per man bash:
Aliases allow a string to be substituted for a word when it is used as
the first word of a simple command.
Stands to reason that if you run ib && is where both ib and is are aliases, it will only run ib.
With that out of the way, there is have a different and, I believe, better solution to your problem. You can use screen to run those 2 commands in the background and also, as a bonus, have the ability to watch their terminal output any time you want.
The idea is this: 1. Start a screen session; 2. Open two windows inside that session; 3. Run npm run start:backend in 1st window and run npm run start:dev in the second window.
Here is what you need:
screen -S Servers -t backend_window -A -d -m
screen -S Servers -X screen -t dev_window
This will start a screen session with backend_window and dev_window inside it. Now you just need to run your 2 commands inside those windows:
screen -S Servers -p backend_window -X stuff $'npm run start:backend\n'
screen -S Servers -p dev_window -X stuff $'npm run start:dev\n'
Now both your npm commands are running in the background at the same time. You can just put these 4 lines into your .bashrc file and it will launch on log in.
But the best part about this approach is you can visually see what's going on with those npm commands by attaching the screen and looking inside those windows. Just run:
screen -rx Servers
This will show you your first window by default. Let's split the screen and show both windows side by side:
Ctr-A + | <- will split the screen into 2 sections
Ctr-A + Tab <- will shit cursor to the new section
Ctr-A + " <- will show you your 2 windows, just pick the dev
All this will give you this view
Keep in mind that both your npm commands will continue to run even after you log out. To kill them, either attach the screen as described above and then Ctrl-C both processes. Or just run killall screen and they will just die.
You could create a function and add your aliases inside, for example,
stopdev () (
cd "$HOME/website" && {
make website_stop
ret=$?
make backend_stop && return $ret
}
)
This example also has a return code, and has a subshell called to run the function, so the filepath is not $HOME/website after the function is called.
More information on the following webpage,
https://unix.stackexchange.com/questions/266063/why-cant-i-call-two-aliases-with

Fixing "Killed: 9" error when running "node"

When I run node I get Killed: 9. I've restarted, uninstalled node, uninstalled npm and uninstalled n and then reinstalled all of them.
After reinstall. Node initially will work, i.e. running node will open a REPL. However, upon running npm install -g n and running n, node becomes broken again.
This is true for every version of node. The executable becomes broken. There's a stack trace to my n installation for failing at this:
execute_with_version() {
test -z $1 && abort "version required"
local version=${1#v}
if [ "$version" = "latest" ]; then
version=$(display_latest_version)
fi
if [ "$version" = "stable" ]; then
version=$(display_latest_stable_version)
fi
if [ "$version" = "lts" ]; then
version=$(display_latest_lts_version)
fi
local bin=${VERSIONS_DIR[$DEFAULT]}/$version/bin/node
shift # remove version
if test -f $bin; then
$bin "$#"
else
abort "$version is not installed"
fi
}
Advice?
Solution (but not really)
Don't use the program, in this case n, after corrupting the process. I switched to nvm and that seems to work. I force terminated a foreman process that was using node. My guess is that it didn't clean up what it needed to and was still being cached even on new installations (please someone correct this).
It happened to me after i accidently involved node's "n" command. Now i ran "n" again
Press enter and everything was fine after.

Running a bash script before startup in an NGINX docker container

I'm trying to run a javascript app on localhost:8000 using docker. Part of what I would like to do is swap out some config files based on the docker run command, I'd like to pass an environment variable into the container so that the bash script can use that as a parameter.
What my dockerfile is looking like is this:
FROM nginx
COPY . /usr/share/nginx/html
CMD ["bash","/usr/share/nginx/html/runfile.sh"]
And the bash script looks like this:
#!/bin/bash
if [ "$SECURITY_VERSION" = "OPENAM" ]; then
sed -i -e 's/localhost/openam/g' authConfig.js
fi
docker run -p 8000:80 missioncontrol:latest -e SECURITY_VERSION="TEST"
Docker gives me an exception saying -e exec command not found.
However if I change the dockerfile to use ENTRYPOINT instead of CMD, the -e flag works but the webserver does not start up.
Is there something I'm missing here? Is the ENTRYPOINT being overriden or something?
EDIT:
So I've updated my dockerfile to use ENTRYPOINT ["bash","/usr/share/nginx/html/runfile.sh", ";", " nginx -g daemon off;"]
But the docker container still shuts down. Is there something I'm missing?
NGINX 1.19 has a folder /docker-entrypoint.d on the root where place startup scripts executed by thedocker-entrypoint.sh script. You can also read the execution on the log.
/docker-entrypoint.sh: /docker-entrypoint.d/ is not empty, will
attempt to perform configuration
/docker-entrypoint.sh: Looking for shell scripts in
/docker-entrypoint.d/
/docker-entrypoint.sh: Launching
[..........]
/docker-entrypoint.sh: Configuration complete; ready for start up
For my future self and everybody else, this is how you can set up variable substitution at startup (for nginx, may also work for other images):
I've also wrote a more in depth blog post about it: https://danielhabenicht.github.io/docker/angular/2019/02/06/angular-nginx-runtime-variables.html
Dockerfile:
FROM nginx
ENV TEST="Hello variable"
WORKDIR /etc/nginx
COPY ./substituteEnv.sh ./substituteEnv.sh
# Execute the subsitution script and pass the path of the file to replace
ENTRYPOINT ["./substituteEnv.sh", "/usr/share/nginx/html/index.html"]
CMD ["nginx", "-g", "daemon off;"]
subsitute.sh: (same as #Daniel West's answer)
#!/bin/bash
if [[ -z $1 ]]; then
echo 'ERROR: No target file given.'
exit 1
fi
#Substitute all environment variables defined in the file given as argument
envsubst '\$TEST \$UPSTREAM_CONTAINER \$UPSTREAM_PORT' < $1 > $1
# Execute all other paramters
exec "${#:2}"
Now you can run docker run -e TEST="set at command line" -it <image_name>
The catch was the WORKDIR, without it the nginx command wouldn't be executed. If you want to apply this to other containers be sure to set the WORKDIR accordingly.
If you want to do the substitution recursivly in multiple files this is the bash script you are looking for:
# Substitutes all given environment variables
variables=( TEST )
if [[ -z $1 ]]; then
echo 'ERROR: No target file or directory given.'
exit 1
fi
for i in "${variables[#]}"
do
if [[ -z ${!i} ]]; then
echo 'ERROR: Variable "'$i'" not defined.'
exit 1
fi
echo $i ${!i} $1
# Variables to be replaced should have the format: ${TEST}
grep -rl $i $1 | xargs sed -i "s/\${$i}/${!i}/Ig"
done
exec "${#:2}"
I know this is late but I found this thread while searching for a solution so thought I'd share.
I had the same issue. Your ENTRYPOINT script should also include exec "$#"
#!/bin/sh
set -e
envsubst '\$CORS_HOST \$UPSTREAM_CONTAINER \$UPSTREAM_PORT' < /srv/api/default.conf > /etc/nginx/conf.d/default.conf
exec "$#"
That will mean the startup CMD from the nginx:alpine container will run. The above script will inject the specified environment variables into a config file. By doing this in runtime yo can override the environment variables.
Update the CMD line as below in the your dockerfile. Please note that if runfile.sh does not succeed (exit 0; inside it) then the next nginx command will not be executed.
FROM nginx
COPY . /usr/share/nginx/html
CMD /usr/share/nginx/html/runfile.sh && nginx -g 'daemon off;'
nginx docker file is using a CMD commnd to start the server on the base image you use. When you use the CMD command in your dockerfile you overwrite the one in their image. As it is mentioned in the dockerfile documentation:
There can only be one CMD instruction in a Dockerfile. If you list more than one CMD then only the last CMD will take effect.
NginX image has docker-entrypoint.d included and on container start will look for any scripts located in there. You can add your custom scripts during docker build. I also found that if you are using alpine image, bash is not installed, so you can add it yourself by running:
RUN apk update
RUN apk upgrade
RUN apk add bash
sample DockerFile:
FROM nginx:alpine
EXPOSE 443
EXPOSE 80
RUN apk update
RUN apk upgrade
RUN apk add bash
COPY ["my-script.sh", "/docker-entrypoint.d/my-script.sh"]
RUN chown nginx:nginx /docker-entrypoint.d/my-script.sh
USER nginx
In order to limit scope execution of your custom script script, it's highly recommended to run your container as a non-privileged user.
nginx container already defines ENTRYPOINT. If you define also CMD it will combine them both like 'ENTRYPOINT CMD' in such way that CMD becomes argument of ENTRYPOINT. That is why you need to redefine ENTRYPOINT to get it working.
Usually ENTRYPOINT is defined in such way, that if you also pass CMD, it will be executed by ENTRYPOINT script. However this might not be case with every container.

Where can I find the node.js file when node is installed?

I've tried to remove this message from node:
(node) warning: Recursive process.nextTick detected
because nothing else works. I've downloaded the source of node from the Ubuntu repository (I use the binary from npm but it should be almost the same, right?) and there is a node.js file containing this:
function maxTickWarn() {
// XXX Remove all this maxTickDepth stuff in 0.11
var msg = '(node) warning: Recursive process.nextTick detected. ' +
'This will break in the next version of node. ' +
'Please use setImmediate for recursive deferral.';
if (process.throwDeprecation)
throw new Error(msg);
else if (process.traceDeprecation)
console.trace(msg);
else
console.error(msg);
}
Where can I find this file when node is installed as a binary?
Node's .js files are compiled into the node binary, so if you want to change this, you will need to check out the git repo, modify the file containing maxTickWarn and then compile Node from source.
Have you tried running node with --no-deprecation?
Usage: node [options] [ -e script | script.js ] [arguments]
node debug script.js [arguments]
Options:
-v, --version print node's version
-e, --eval script evaluate script
-p, --print evaluate script and print result
-i, --interactive always enter the REPL even if stdin
does not appear to be a terminal
--no-deprecation silence deprecation warnings
--trace-deprecation show stack traces on deprecations
--v8-options print v8 command line options
--max-stack-size=val set max v8 stack size (bytes)

is it possible to run JSLint as commandline in windows with help of node.js?

I mean to run it like this:
node.exe lint.js my_js_file.js
And then get output to a console.
What do I need to download ? Do I need just to save http://www.jslint.com/ to disk and then grab some attached js file or I need to look for special version for node.js ?
Install jshint globally then you can use it from the command line.
npm install -g jshint
jshint testfile.js
All this is assuming that you already have node and npm running on you windows machine.
Edit
I just noticed that I responded with an answer for jshint instead of jslint, the as the other answer points out, they are similar but not the same. My answer holds true for both though.
For jslint:
npm install -g jslint
jslint testfile.js
March's answer is for jsHint. Minor changes for jsLint, with an "L", if that's precisely what you want.
Here's a decent guide for Ubuntu. Most of it translates:
http://blog.simplytestable.com/installing-jslint-for-command-line-use-on-ubuntu/
So once you've installed node, you can do the following:
C:\Users\YourName>mkdir C:\usr\share\node-jslint
C:\Users\YourName>cd C:\usr\share\node-jslint
C:\usr\share\node-jslint>npm install jslint
npm http GET https://registry.npmjs.org/jslint
npm http 200 https://registry.npmjs.org/jslint
npm http GET https://registry.npmjs.org/jslint/-/jslint-0.2.10.tgz
npm http 200 https://registry.npmjs.org/jslint/-/jslint-0.2.10.tgz
npm http GET https://registry.npmjs.org/nopt
npm http 200 https://registry.npmjs.org/nopt
npm http GET https://registry.npmjs.org/nopt/-/nopt-1.0.10.tgz
npm http 200 https://registry.npmjs.org/nopt/-/nopt-1.0.10.tgz
npm http GET https://registry.npmjs.org/abbrev
npm http 200 https://registry.npmjs.org/abbrev
npm http GET https://registry.npmjs.org/abbrev/-/abbrev-1.0.4.tgz
npm http 200 https://registry.npmjs.org/abbrev/-/abbrev-1.0.4.tgz
jslint#0.2.10 node_modules\jslint
+-- nopt#1.0.10 (abbrev#1.0.4)
Note that I borrowed the path from the Ubuntu directions for my C:\ drive. You can put the jslint module wherever you want. Just ensure that you change the path in the jslint call, below.
Now I can run jslint against any file I want using the jslint module I've installed. I downloaded jQuery development 1.11 just for fun, and saved it to c:\temp\jquery-1.11.0.js. So let's jslint it.
C:\usr\share\node-jslint>node C:/usr/share/node-jslint/node_modules/jslint/bin/jslint.js c:\temp\jquery-1.11.0.js
c:\temp\jquery-1.11.0.js
#1 Expected exactly one space between 'function' and '('.
(function( global, factory ) { // Line 15, Pos 10
#2 Unexpected space between '(' and 'global'.
(function( global, factory ) { // Line 15, Pos 12
#3 Unexpected space between 'factory' and ')'.
(function( global, factory ) { // Line 15, Pos 28
#4 Use spaces, not tabs.
if ( typeof module === "object" && typeof module.exports === "object" ) { //
Line 17, Pos 1
...
Etc etc. I'm in C:\usr\share\node-jslint, above, but I've used the full path to jslint.js, so I can use the same call anywhere.
And you're linting.
install Node;
run npm install jshint -g from CMD
add "C:\Users\xxx\AppData\Roaming\npm\" to "%Path%"

Categories