Can't get color output in Node - node.js

I'm trying to log to the console in different colors using chalk but I haven't gotten it to work. I have a file that consists of the following two lines and I'm running it with the command node test.js
var chalk = require('chalk');
console.log(chalk.red('Hello'));
// outputs 'hello' in black
The following command does output in red so I know that it's possible in my terminal.
node <<< "console.log('\x1b[31mhello\x1b[m')"
I have "chalk": "^2.1.0" in my dev dependencies and have run a npm install. The following shows some of my setup.
$ node --version
v8.2.1
$ echo $TERM
xterm-256color
$ echo $SHELL
/bin/bash
$ echo $TERM_PROGRAM
Apple_Terminal
Any ideas?
Additionally:
It looks like chalk isn't outputting the ansi codes at all for some reason...
console.log(util.inspect('hello'));
//'hello'
console.log(util.inspect(chalk.red('hello')));
// 'hello'
console.log(util.inspect('\x1b[31mhello\x1b[m'));
// '\u001b[31mhello\u001b[m'

I was having a very similar issue. This answer is for anyone else in the future.
Turns out that chalk won't apply styles if you are piping the output somewhere.
In my npm scripts, I was using:
node export.js | tee export.log
Since I was switching to use Winston for logging anyway, and it can output to different files via 'transports', I no longer need the output piped somewhere and chalk is free to work.
Hope this helps someone!

Uninstalling and reinstalling the package fixed the problem.
npm remove -D chalk
npm i -D chalk

In my case, it works locally. But it doesn't work on the CICD pipeline.
The solution is to set the following environment variable of your CICD pipeline:
FORCE_COLOR=1

Try this version
npm install chalk#4.1.2

Related

How use backticks in npm scripts on windows

My workflow is npm scripts, running commands in my node_modules along with simple shell commands.
Unfortunately this makes it difficult for windows users due to my using backticks in some commands (see Example below). I have a pull request volunteering to convert to shellJS/shx for my build so my repo will build cross-platform but we can't figure out a solution for backticks in npm scripts.
Question:
What shell does npm use? On windows it appears to not support backticks.
Is there a workaround? Piping doesn't help, alas, rm, mkdir etc don't use stdin.
Example backtick use in package.json:
"mkdirs": [
"dist/AS",
"libs",
"models/scripts"
],
"scripts": {
"mkdirs": "mkdir -p `bin/pkgkey.js mkdirs`",
....
.. where the bin/pkgkey.js mkdirs script simply returns the mkdirs array. This may seem odd but it's great for organizing npm-style workflow.
The pkgkey script (simplified):
#!/usr/bin/env node
const fs = require('fs')
const json = JSON.parse(fs.readFileSync('package.json'))
const key = process.argv[2]
let val = json[key]
if (Array.isArray(val)) val = val.join(' ')
process.stdout.write(val)
Check cross-env, don't know if it will work for your use case but I use it to make npm scripts platform independent
npm i --save-dev cross-env
"mkdirs": "cross-env mkdir -p ..."
https://www.npmjs.com/package/cross-env

Force yarn install instead of npm install for Node module?

I want to force using yarn install instead of npm install. I want to raise an error in npm install. What should I do in package.json?
UPDATE: Alexander's answer is the better solution and uses the same technique I describe here. I am leaving my answer in tact for posterity. The original point of my answer was to show that you can execute a small node script which should work on all platforms.
In your preinstall script you can run a mini node script which should work on all platforms, whereas things like pgrep (and other common *nix commands and operators) won't work on Windows until Windows 10 has received widespread adoption.
I tested the below script on Node v4.7.0 (npm v2.15.11) and Node v7.2.1 (npm v3.10.10). I assume it works on everything in between. It works by checking the environment variables on the currently running process - the npm_execpath is the path to the currently running "npm" script. In the case of yarn, it should point to /path/to/yarn/on/your/machine/yarn.js.
"scripts": {
"preinstall": "node -e \"if(process.env.npm_execpath.indexOf('yarn') === -1) throw new Error('You must use Yarn to install, not NPM')\""
}
You can read more about npm scripts here: https://docs.npmjs.com/misc/scripts
As far as the npm_execpath environment variable, while not documented I doubt that it will ever change. It's been around for multiple major releases of npm and it doesn't really pass the "there's a better name for this" test.
Most of the answers here involve hacky scripts but there's a built in way to achieve this which I posted over on the Yarn github issue. Unlike soe of the other ways, this works for any and all NPM commands -- actually a bug in npm means it blocks npm install but not npm install <package>. Hopefully though the developers suspicions would already be raised from doing an npm install.
You add a fake engine version like so in package.json (you may want to tweak the yarn and node entries):
"engines": {
"npm": "please-use-yarn",
"yarn": ">= 1.17.3",
"node": ">= 12.5.0"
}
Then you add an .npmrc file to the project root with this:
engine-strict = true
Running NPM then raises an error:
npm ERR! code ENOTSUP
npm ERR! notsup Unsupported engine for root#: wanted: {"npm":"please-use-yarn","yarn":">= 1.17.3","node":">= 12.5.0"} (current: {"node":"12.9.1","npm":"6.10.2"})
npm ERR! notsup Not compatible with your version of node/npm: root#
Like the other answers, I'd recommend using a preinstall script and checking your environment. For a portable solution that won't have false-positives if another npm process happens to be running, using node -e 'JS_CODE' is probably the best option.
In that JS code, you can check the package manager's path using the following:
process.env.npm_execpath
Yarn's binary is yarn.js, compared to npm-cli.js used by NPM. We can use a regex like the following to check that this string ends with yarn.js.
/yarn\.js$/
By using this regex, we can be sure it won't accidentally match somewhere earlier in the file system. Most-likely yarn won't appear in the file path, but you can never be too sure.
Here's a minimal example:
{
"name": "test",
"version": "1.0.0",
"scripts": {
"preinstall": "node -e 'if(!/yarn\\.js$/.test(process.env.npm_execpath))throw new Error(\"Use yarn\")'"
}
}
Of course, the user will still be able to get around this check be editing the JSON or using the --ignore-scripts options:
npm install --ignore-scripts
After trying these options and not being very satisfied, I recommend only-allow.
Just add:
{
"scripts": {
"preinstall": "npx only-allow yarn"
}
}
I like that it provides a clear warning message, and instructions how to install yarn:
Credit to Adam Thomas' answer for providing the thread recommending this.
You can use the preinstall hook along with some shell script to achieve this.
sample package.json:
"scripts": {
"preinstall": "pgrep npm && exit 1"
}
I've just released a module that includes a CLI for this (useful for npm preinstall scripts): https://github.com/adjohnson916/use-yarn
Also, I've just released a helper for Danger to check for missing yarn.lock changes on CI:
https://github.com/adjohnson916/danger-yarn-lock
See also discussion here:
https://github.com/yarnpkg/yarn/issues/1732
https://github.com/alexanderwallin/use-yarn-instead/issues/1
If you want to simply test whether packages are being installed under yarn or npm, I tweaked Alexander O'Mara's answer slightly since it worked for me on OS X:
"scripts": {
"preinstall": "if node -e \"process.exitCode=!/yarn\\.js$/.test(process.env.npm_execpath)\" ; then echo yarn ; else echo npm ; fi",
"postinstall": ""
}
There are quite a few concepts happening in this short snippet:
The \\. portion is escaped so that \\ becomes \ and results in a properly escaped \. to detect a period in the regex.
process.exitCode= can be used to set the process's exit code and is safer than calling process.exit(N) due to the asynchronous nature of Node.js.
In Alexander's example, throw new Error(\"Use yarn\") caused node to exit with code 1 and print the stack trace to stderr. You can try running these on the console to see how that works: node -e 'throw new Error("Oops")' and node -e 'throw new Error("Oops")' 2> /dev/null (which directs the stderr stream to /dev/null). Then you can verify that the exit code was 1 with echo $? (which prints the last exit code).
The shell's if XXXX ; then YYYY ; else ZZZZ ; fi conditional logic checks the exit code of XXXX and goes to the then case for 0 (any other value goes to the else case). So if the regex detects yarn.js at the end of process.env.npm_execpath then it returns true. This must be negated so that the node process exits with code 0 and satisfies the if.
You could also console.log() the regex result and compare the output in the shell (this is just a little more verbose). Here are some examples of how to do that: https://unix.stackexchange.com/a/52801 and https://superuser.com/a/688902
You can append true ; or false ; to any shell statement to set the exit code manually. For example you can try true ; echo $? or false ; echo $?.
You can also leave off the else echo npm ; portion entirely if you don't need it.
With all of that out of the way, you can substitute the echo yarn and echo npm portions with other commands. For example, you could put multiple commands in a subshell like (echo yarn) or echo $(echo yarn).
In my case, I needed to work around an issue where one of the packages installed but had bugs under yarn so I had to run an npm install --ignore-scripts in the success case. Note that this should probably never be done in production, but can be a lifesaver if you just need to get something done or don't have control over which package manager will be used down the road.
I haven't tried this on Windows, so if someone can test the syntax there I will update my answer with what works. It would be best if the preinstall script is identical under both Windows and the Mac/Linux shell.
Found an alternate solution on Reddit. I added this to the end of my .zshenv file:
NPM_PATH=$(which npm)
npm () {
if [ -e yarn.lock ]
then
echo "Please use yarn with this project"
else
$NPM_PATH "$#"
fi
}
It now stops me from absentmindedly running commands like npm i on any yarn project on my Mac.
As some answers have already showed, you can use the only-allow package like so:
{
"scripts": {
"preinstall": "npx only-allow [npm|cnpm|pnpm|yarn]"
}
}
However, NodeJS v16.9.0 and v14.19.0 support a new experimental packageManager field in the package.json file.
Type: <string>
{
"packageManager": "<package manager name>#<version>"
}
The "packageManager" field defines which package manager is expected to be used when working on the current project. It can be set to any of the supported package managers, and will ensure that your teams use the exact same package manager versions without having to install anything else other than Node.js.
This field is currently experimental and needs to be opted-in; check the Corepack page for details about the procedure.

jsx command not found on mac terminal

Problem:
I execute the following command from the macintosh terminal:
$ jsx --watch src/ build/
I recieve the following output error from the terminal:
-bash: jsx: command not found
Relevant information:
I am following the following tutorial: https://facebook.github.io/react/docs/getting-started.html
I executed the following command from the tutorial with positive output:
$ npm install -g react-tools
This instruction immediately precedes the instruction that produces the error:
Environment information:
$ node -v
v0.12.4
$ npm
2.10.1
Best of google:
https://groups.google.com/forum/#!topic/reactjs/TUBkgptg2dM
Adtional Notes:
Best of google is short because there aren't many links that provide information that the tutorial provides. A result of this is that I think there is an obvious solution and that I am just being dumb.
I will provide more information if requested
Please excuse the format of this question. This is how I solve a problem. I'm hoping someone can provide the Solution points. I apologize if this is over-the-top for a simple question, but I couldn't find any rules against it.
Solution to my unique problem:
Execute the following command:
$ export PATH=$PATH:$(npm config get prefix)/bin
Original problem command:
$ jsx --watch src/ build/
New positive output:
built Module("helloworld")
["helloworld"]
run this:
npm config get prefix
that will give you a clue as to where your global npm modules are installed. you need to add the bin directory under the directory returned by the above to your path. for example, it might return /usr/local, in which case you should add /usr/local/bin to your PATH. You could just do:
export PATH=$PATH:$(npm config get prefix)/bin

browserify doing nothing from command line

I'm totally new to node.js, so I'm guessing this is a dumb question..
I have an ubuntu machine, on which I have installed browserify with npm:
sudo npm install browserify -g
I can require this module if I open a node.js shell, but when I try to run it from the command line nothing happens:
ubuntu:~$ browserify
ubuntu:~$ browserify f -o f3
ubuntu:~$
whats going on here? The command is found but does nothing and prints nothing??
Thanks
The problem is probably with 'node' vs 'nodejs' environment.
Type which browserify in your terminal and then edit the file with your preferred text editor: emacs /usr/local/bin/browserify.
The very first line of the file might read something like #!/usr/bin/env node. Just change it to call nodejs instead of node so that it reads #!/usr/bin/env nodejs
This has to be the the easiest way. And it works with many other tools that depend on node (like coffeescript relp/compiler, mocha testing tool and pretty much anything else that depends on node)
do you have f in current path and have you checked if f3 is generated?
i see usually output to stdout and redirect to bundle by >, like below:
browserify f.js > f3.js

npm postinstall fails with multiple commands

Inside my composer.json, there's a postinstall hook setup like the following:
"scripts" : {
"dist" : "node dist; node_modules/.bin/doccoh src/package.js",
"postinstall" : "node_modules/.bin/grunt setup || true; node_modules/.bin/bower install",
"start" : "node server.js"
}
Whenever I run it (on Win from Git/Gnu Bash CLI), I end with
command not found. either the command was written wrong or couldn't be found
Rough translation from German CLI error.
I tried splitting it into multiple ;/semicolon separated parts and first cd into that directory, but it simply ends up with the same error message. Replacing the whole postinstall command set with a simple ls does work. So I guess the problem might be the semicolon separation or a wrong usage of commands. But overall I got no idea what's wrong.
Note: I got grunt-cli version 0.1.9 and grunt version 0.4.1 installed globally.
I'm a bit late to answer, but if you're on Windows, multiple commands on a single line are executed with the use of &&
postinstall: "some command && some other -c"
I ran into this looking for something and thought this may help other people. I have found it easier to move to postinstall.js files as things get a little complicated. This makes it easier to deal with moving forward.

Resources