Problems creating a React-node app with npm - node.js

The instructions are as following:
You are about to start creating a React-node app. Create the file
package.json using npm commands.
Make use of the following information:
The name of the app should be npm_package. The start point will be
index.js The project should have the following elements of
dependencies
- Install the latest version of react
- Lodash with major version 4 and minor version 17,
- Redux with Major version 4,
- Mocha for testing in Dev,
- Eslint with major version 6 in Dev.
Here is my virtual environment for reference:
Virtual Environment
I tried the following commands:
npm init -y
npm install react --save
npm install lodash#4.17.0 --save
npm install redux#4.0.0 --save
npm install mocha --save-dev
npm install eslint#6.0.0 --save-dev
Correctness is determined by the test file score.sh:
#!/bin/sh
PASS=0
FAIL=0
TEST_1=$(grep -o -e "\"dependencies\"" -e "react" -e "\"redux\":\s*\"\^4.*\"" -e "\"lodash\":\s*\"\^4.17.*\"" /projects/challenge/package.json| wc -l)
TEST_2=$(grep -o -e "\"devDependencies\":\s*{" -e "\"eslint\":\s*\"^6.*\"" -e "\"mocha\":\s*" /projects/challenge/package.json| wc -l)
TEST_3=$(find /projects/challenge/node_modules | wc -l)
TEST_4=$(grep -o -e "\"name\":\s*\"npm_package\"" /projects/challenge/package.json| wc -l)
if [ "$TEST_1" -eq 4 ]
then ((PASS++))
fi;
if [ "$TEST_2" -eq 3 ]
then ((PASS++))
fi;
if [ "$TEST_3" -ge 1 ]
then ((PASS++))
fi;
if [ "$TEST_4" -eq 1 ]
then ((PASS++))
fi;
FAIL=$(( 4 - $PASS ))
echo "Test cases executed = 4";
echo "PASS = $PASS FAIL=$FAIL"
Here is my console when I run the tests:
user#workspace5zx0357qxb7p4nvt:/projects/challenge$ bash score.sh Test
cases executed = 4 PASS = 3 FAIL=1
user#workspace5zx0357qxb7p4nvt:/projects/challenge$
It does not tell me which test failed (or much of any other information) and therefore I dont know which of my commands I inputted is wrong or am I missing commands

Since no one has decided to reply, let me.
Just go into package.json and change the name to npm_package.

Related

npm - How to set max-old-space-size in npm

I am getting the below error while building the angular project,
CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory
I have seen somewhere that configuring max-old-space-size in npm will solve the issue. But I don't know how to set it. I am using Windows OS & there are two npm files inside the nodejs installation folder (C:\Program Files\nodejs), npm & npm.cmd. First line inside the npm.cmd file is "Created by npm, please don't edit manually". So I am not supposed to edit this file & I have to configure max-old-space-size inside npm file. But I don't where in this file I have to configure it. My npm file looks like below,
#!/bin/sh
(set -o igncr) 2>/dev/null && set -o igncr; # cygwin encoding fix
basedir=`dirname "$0"`
case `uname` in
*CYGWIN*) basedir=`cygpath -w "$basedir"`;;
esac
NODE_EXE="$basedir/node.exe"
if ! [ -x "$NODE_EXE" ]; then
NODE_EXE=node
fi
NPM_CLI_JS="$basedir/node_modules/npm/bin/npm-cli.js"
case `uname` in
*MINGW*)
NPM_PREFIX=`"$NODE_EXE" "$NPM_CLI_JS" prefix -g`
NPM_PREFIX_NPM_CLI_JS="$NPM_PREFIX/node_modules/npm/bin/npm-cli.js"
if [ -f "$NPM_PREFIX_NPM_CLI_JS" ]; then
NPM_CLI_JS="$NPM_PREFIX_NPM_CLI_JS"
fi
;;
*CYGWIN*)
NPM_PREFIX=`"$NODE_EXE" "$NPM_CLI_JS" prefix -g`
NPM_PREFIX_NPM_CLI_JS="$NPM_PREFIX/node_modules/npm/bin/npm-cli.js"
if [ -f "$NPM_PREFIX_NPM_CLI_JS" ]; then
NPM_CLI_JS="$NPM_PREFIX_NPM_CLI_JS"
fi
;;
esac
"$NODE_EXE" "$NPM_CLI_JS" "$#"
Possibly you could try this,
> npm run start --node-flags --max-old-space-size=512 --no-warnings
> node --max-old-space-size=250 `which npm` some_npm_command
I faced similar issue but i had to increase docker memory size.

Check if package.json has script with a certain name in shell script without using extra NPM packages

I am testing a larger library of NPM packages, that consists of private packages, altered forks of public packages or downstreams of public packages.
lib
|-package_1
|-package_2
|-package_N
So I am running a shell script through my package lib, that runs in each directory the npm test command.
for D in *; do
if [ -d "${D}" ]; then
echo "================================="
echo "${D}" # PRINT DIRECTORY NAME
echo "================================="
cd $D
npm run tests
cd ../ # LEAVE PACKAGE DIR
fi
done
Unfortunately there is not a unique pattern for naming the tests-script in the package's JSON files. Some package are running under test a script with watch-mode and have a different name for their cli script (mostly named testcli).
What I would like to do is something like the following pseudocode:
if has-testcli-script then
npm run testcli
else
npm run test
I assume for now, that only those two options exist. I am rather interested in the way of knowing if the script exists, without installing an additional global NPM package.
Since npm version 2.11.4 at least, calling npm run with no arguments will list all runable scripts. Using that you can check to see if your script is present. So something like:
has_testcli_script () {
[[ $(npm run | grep "^ testcli" | wc -l) > 0 ]]
}
if has_testcli_script; then
npm run testcli
else
npm test
fi
Or alternatively, just check to see if your script is in the package.json file directly:
has_testcli_script () {
[[ $(cat package.json | grep "^ \"testcli\":" | wc -l) > 0 ]]
}
In my case that approach didn't work and I had to implement something using jq instead.
has_script (script) {
[[ ! -z "$(jq -rc --arg key $script '.scripts | to_entries | .[] | select(.key == \$key)' package.json)" ]]
}
then use it as:
if has_script('testcli'); then
// Do something
else
// Do nothing
fi

Install node on ubuntu 17.04

I installed node 8.0.0 on Ubuntu then followed this answer to make it work but now when typing node -v it says v4.7.2. I'd like to have v.8. The one I'm trying to install. Is it a problem with the symlink or what's up ?
(Ubuntu 17:04)
I suggest you remove the ubuntu package
sudo apt-get remove --purge nodejs-*
then execute below shell script to install nodejs ... you must update your ~/.bashrc with a copy N paste of the lines mentioned in below ... vi install_node.sh
#!/bin/bash
# ............... top of cut ........................ install_node.sh
export NODE_VER=v8.0.0 # see available versions at https://nodejs.org/dist/
# pick parent dir of nodejs install ... comment out or remove ONE of below
# export CODE_PARENT_DIR=/opt/code # root owned dir ... requires you to sudo prior to npm install going forward
export CODE_PARENT_DIR=${HOME} # RECOMMENDED execute as yourself including npm install
# ......... following env vars are OK no edits needed
curr_OS=$( uname )
if [[ "${curr_OS}" == "Darwin" ]]; then
OS_ARCH=darwin-x64
elif [[ "${curr_OS}" == "Linux" ]]; then
OS_ARCH=linux-x64
else
echo "ERROR - failed to recognize OS $curr_OS"
exit 5
fi
if [[ -z ${CODE_PARENT_DIR} ]]; then
echo "ERROR - failed to see env var CODE_PARENT_DIR"
exit 5
fi
export NODE_CODEDIR=${CODE_PARENT_DIR}/nodejs
export COMSUFFIX=tar.gz
export NODE_NAME=node-${NODE_VER}
export NODE_PARENT=${NODE_CODEDIR}/${NODE_NAME}-${OS_ARCH}
export PATH=${NODE_PARENT}/bin:${PATH}
export NODE_PATH=${NODE_PARENT}/lib/node_modules
# ............... end of cut ........................ install_node.sh
# copy and paste above from ... top of cut ... to here into your file ~/.bashrc
echo
echo "NODE_CODEDIR $NODE_CODEDIR<--"
echo
echo "mkdir -p ${NODE_CODEDIR}"
echo
mkdir -p ${NODE_CODEDIR}
echo
echo "cd ${NODE_CODEDIR}"
cd ${NODE_CODEDIR}
echo
# this is compiled code NOT source
[ -f ${NODE_NAME}-${OS_ARCH}.${COMSUFFIX} ] && rm ${NODE_NAME}-${OS_ARCH}.${COMSUFFIX} # if file exists remove
echo "wget -q --show-progress https://nodejs.org/download/release/${NODE_VER}/${NODE_NAME}-${OS_ARCH}.${COMSUFFIX}"
wget -q --show-progress https://nodejs.org/download/release/${NODE_VER}/${NODE_NAME}-${OS_ARCH}.${COMSUFFIX}
echo
echo "tar -C ${NODE_CODEDIR} -xf ${NODE_NAME}-${OS_ARCH}.${COMSUFFIX}"
tar -C ${NODE_CODEDIR} -xf ${NODE_NAME}-${OS_ARCH}.${COMSUFFIX}
echo
[ -f ${NODE_NAME}-${OS_ARCH}.${COMSUFFIX} ] && rm ${NODE_NAME}-${OS_ARCH}.${COMSUFFIX} # if file exists remove
# ........... done ........... #
which node
node --version
# .... bottom of file install_node.sh

Can I inspect the contents of an npm package before publish?

I would like to be able to run a script on the contents of a npm package before it gets published to see if all the required files are presents. We recently had some published packages that were missing things as they had wrongfully been matched by patterns in .npmignore.
Is this possible? Will npm install . -g essentially do this by placing the exact same contents in /usr/local/lib/node_modules/mypackage as on NPM?
npm pack --dry-run will output the to-be-published files to stderr, without doing any changes to the filesystem.
npm notice 📦 #some/package#0.2.38
npm notice === Tarball Contents ===
npm notice 641B package.json
npm notice 961B src/index.js
npm notice === Tarball Details ===
npm notice name: #some/package
npm notice version: 0.2.38
npm notice filename: some-package-0.2.38.tgz
npm notice package size: 1 kB
npm notice unpacked size: 1.5 kB
npm notice shasum: somesha
npm notice integrity: someothersha
npm notice total files: 2
You could assert on that list of files with a file that doesn't exist, e.g.
> npm pack --dry-run 2>&1 >/dev/null | grep src/someFileNotInPackage.js
> echo $?
1
Notice the 1, an error exit code.
Or on a file that does exist:
> npm pack --dry-run 2>&1 >/dev/null | grep src/index.js
> echo $?
0
Notice the 0, success exit code.
This scripts checks for the files you pass in as params:
#!/bin/bash
# Checks to see if the published NPM package has the files passed in as arguments
# Requirements: jq and npm
# `brew install jq` on macOS and `apt install jq` on Ubuntu
pkg=$(echo $(jq .name package.json)-$(jq .version package.json).tgz | sed 's/"//g')
files_to_check="$#"
main(){
npm pack > /dev/null 2>&1;
check_tarball_files $#
rm $pkg > /dev/null;
}
usage(){
cat << EOF
Usage: check-files-present [file1 [file2 [...]]]
Example. Want to see that 'lolex' contains two specific files:
check-files-present src/lolex-src.js package/lolex.js
EOF
exit 1
}
if [[ $# == 0 ]]; then
echo No file names given on command line
usage
fi
check_tarball_files(){
tarball_files=$(tar tf $pkg)
for f in $files_to_check; do
if !(echo $tarball_files | grep package/$f) > /dev/null; then
echo "Missing $f" && exit 1
fi
done
echo All files present: $files_to_check
}
main
Gist
I run npm pack && tar -xvzf *.tgz | cut -c9- && rm -rf package *.tgz with Git Bash on Windows to list all files to be included in the published package.
For example, running the script on the axios repository:
git clone https://github.com/axios/axios.git
cd axios
npm install
npm run build
Pack, extract the archive, trim package/ prefix and cleanup afterward:
npm pack && tar -xvzf *.tgz | cut -c9- && rm -rf package *.tgz
This results in a list of files included in the package to be deployed:
axios-0.19.0.tgz
LICENSE
dist/axios.js
lib/axios.js
lib/core/Axios.js
dist/axios.min.js
lib/helpers/bind.js
lib/core/buildFullPath.js
lib/helpers/buildURL.js
lib/cancel/Cancel.js
lib/cancel/CancelToken.js
lib/helpers/combineURLs.js
lib/helpers/cookies.js
lib/core/createError.js
lib/defaults.js
lib/helpers/deprecatedMethod.js
lib/core/dispatchRequest.js
lib/core/enhanceError.js
lib/adapters/http.js
index.js
lib/core/InterceptorManager.js
lib/helpers/isAbsoluteURL.js
lib/cancel/isCancel.js
lib/helpers/isURLSameOrigin.js
lib/helpers/isValidXss.js
lib/core/mergeConfig.js
lib/helpers/normalizeHeaderName.js
lib/helpers/parseHeaders.js
lib/core/settle.js
lib/helpers/spread.js
lib/core/transformData.js
lib/utils.js
lib/adapters/xhr.js
package.json
dist/axios.map
dist/axios.min.map
CHANGELOG.md
lib/adapters/README.md
lib/core/README.md
lib/helpers/README.md
README.md
UPGRADE_GUIDE.md
index.d.ts
The first line should be skipped as it is the name of the archive (package and version).

How to run npm sh script on Windows and Unix

I want to run a sh script that detects my npm version via npm scripts.
I have the following script and it works cool:
if [ $(npm -v | cut -c 1 | awk '{print $1\"<3\"}' | bc -l) != 0 ]; then echo '[ERROR] You need npm version #>=3\n' && false; fi
But this script works only on *NIX when I run the script on windows I got a error:
$(npm was unexpected at this time.
I want to detect if I'm running the script on Windows then don't execute the script, I tried this, but again only works on *NIX:
if [ 'uname -s' != CYGWIN* ]; then if [ $(npm -v | cut -c 1 | awk '{print $1\"<3\"}' | bc -l) != 0 ]; then echo '[ERROR] You need npm version #>=3\n' && false; fi; fi
Then I got:
'uname was unexpected at this time.
I was checking that the equivalent of uname on windows is systeminfo
But if I use systeminfo then I got the undefined on *NIX.
Any ideas of how can I make this script work on Windows && *NIX?
If you want to execute your bash script on a platform that is not Windows you could check the platform with node itself (assuming that node is installed) using os.platform()
scripts: {
checkNpmVersion: "node -e \"process.exit(require('os').platform() === 'win32')\" && ./check-npm.sh"
}
Or even better you could write your little script in node so that it works on any platform (again assuming that node is installed)
// check-npm.js
const exec = require('child_process').exec
exec('npm -v', function (err, stdout, stderr) {
if (err) throw err
if (stdout.match(/^3/)) throw "npm>3 required"
})
And in the scripts field
scripts: {
checkNpmVersion: "node check-npm.js"
}
Tested on Win7 with Node v4.4.5 and npm 2.15.5

Resources