Node.js Command Line Console Log Level - node.js

How do you set the log level for node when starting it from the command line? I admit, i'm a node.js newbie, but looking for something like node myapp.js --loglevel warn

You can overwrite the console.log,console.debug,console.error,console.warn functions to allow logLevels.
Check out my snippet written in typescript:
export type LogLevel = "debug" | "log" | "warn" | "error" | "none";
let logLevels = ["debug", "log", "warn", "error", "none"];
let shouldLog = (level: LogLevel) => {
// #ts-ignore
return logLevels.indexOf(level) >= logLevels.indexOf(global.logLevel);
};
// #ts-ignore
global.logLevel = "debug";
let _console=console
global.console = {
...global.console,
log: (message?: any, ...optionalParams: any[]) => {
shouldLog("log")&&_console.log(message, ...optionalParams);
},
warn: (message?: any, ...optionalParams: any[]) => {
shouldLog("warn") && _console.warn(message, ...optionalParams);
},
error: (message?: any, ...optionalParams: any[]) => {
shouldLog("error") && _console.error(message, ...optionalParams);
},
debug: (message?: any, ...optionalParams: any[]) => {
shouldLog("debug") && _console.debug(message, ...optionalParams);
},
};
Then you can use the console functions as usual and set the logLevel with globals.logLevel="warn",...

Not possibly quite what you are after but you can enable debugging within node by setting a NODE_DEBUG environment variable first.
E.g. export NODE_DEBUG="net" && node myapp.js will give debugging for network related node operations.
https://github.com/joyent/node/blob/master/lib/net.js#L66

Related

Switching Storybook from Webpack to Vita in Gatsby app

I work on a Gatsby project and I'm hoping to run our Storybook with Vita instead of our existing Webpack setup. I'm clearly not doing it right.
I added the plugins:
"#storybook/builder-vite": "^0.4.2",
"#vitejs/plugin-react": "^3.1.0",
"vite": "^4.1.1",
I also added our aliases by importing my tsconfigand converting the paths to the right format.
Although most of my attempts to run it resulted in about 1000 instances of
Failed to resolve import "react/jsx-dev-runtime" from "react/jsx-dev-runtime". Does the file exist?
it's actually running now. And it booted up WAY faster than it used to.
The only issue appears to be that it's not reloading, not at all. I make a change in a component, or a change in a story, and there is zero output in the terminal running storybook.
Although I do notice that this run, although it looks like it's working in the browser, does still give only these two errors:
Failed to resolve dependency: react/jsx-runtime, present in 'optimizeDeps.include'
Failed to resolve dependency: react/jsx-dev-runtime, present in 'optimizeDeps.include'
How can I fix this? I'm so close!
I've tried...
const react = require('#vitejs/plugin-react');
//...
module.exports = {
// ...
async viteFinal(config) {
return mergeConfig(config, {
// is this where this goes?
plugins: [
react({
jsxRuntime: 'classic',
}),
],
resolve: { alias: aliasPathsVite },
},
})
},
}
Which does open Storybook in the browser, but it doesn't load, and the terminal gives endless instances of:
10:30:38 AM [vite] Internal server error: Transform failed with 2 errors:
Typography/Links.tsx:3:4: ERROR: The symbol "prevRefreshReg" has already been declared
Typography/Links.tsx:4:4: ERROR: The symbol "prevRefreshSig" has already been declared
Plugin: vite:esbuild
File: Typography/Links.tsx:1:42
The symbol "prevRefreshReg" has already been declared
1 | import RefreshRuntime from "/#react-refresh";let prevRefreshReg;let prevRefreshSig;if (import.meta.hot) { if (!window.__vite_plugin_react_preamble_installed__) { throw new Error( "#vitejs/plugin-react can't detect preamble. Something is wrong. " + "See https://github.com/vitejs/vite-plugin-react/pull/11#discussion_r430879201" ); } prevRefreshReg = window.$RefreshReg$; prevRefreshSig = window.$RefreshSig$; window.$RefreshReg$ = (type, id) => { RefreshRuntime.register(type, "Typography/Links.tsx" + " " + id) }; window.$RefreshSig$ = RefreshRuntime.createSignatureFunctionForTransform;}var _jsxFileName = "Typography/Links.tsx";
2 | import RefreshRuntime from "/#react-refresh";
3 | let prevRefreshReg;
| ^
4 | let prevRefreshSig;
5 | if (import.meta.hot) {
The symbol "prevRefreshSig" has already been declared
2 | import RefreshRuntime from "/#react-refresh";
3 | let prevRefreshReg;
4 | let prevRefreshSig;
| ^
5 | if (import.meta.hot) {
6 | if (!window.__vite_plugin_react_preamble_installed__) {
at failureErrorWithLog (node_modules/esbuild/lib/main.js:1604:15)
at node_modules/esbuild/lib/main.js:837:29
at responseCallbacks.<computed> (node_modules/esbuild/lib/main.js:701:9)
at handleIncomingPacket (node_modules/esbuild/lib/main.js:756:9)
at Socket.readFromStdout (node_modules/esbuild/lib/main.js:677:7)
at Socket.emit (node:events:513:28)
at addChunk (node:internal/streams/readable:315:12)
at readableAddChunk (node:internal/streams/readable:289:9)
at Socket.Readable.push (node:internal/streams/readable:228:10)
at Pipe.onStreamRead (node:internal/stream_base_commons:190:23)
I've tried...
module.exports = {
// ...
async viteFinal(config) {
return mergeConfig(config, {
resolve: {
alias: {
...aliasPathsVite,
'react/jsx-runtime': path.join(
__dirname,
'node-modules/react/jsx-runtime'
),
},
optimizeDeps: {
include: ['react/jsx-runtime']
}
},
})
},
}
which opens a non-working Storybook in the browser, and the terminal says this hundreds of times
Failed to resolve import "react/jsx-dev-runtime" from "react/jsx-dev-runtime". Does the file exist?
Then some of these:
[vite] error while updating dependencies:
Error: ENOENT: no such file or directory, rename 'node_modules/.vite-storybook/deps_temp' -> 'node_modules/.vite-storybook/deps'
at renameSync (node:fs:1030:3)
at Object.commit (file:///node_modules/vite/dist/node/chunks/dep-3007b26d.js:42874:19)
at runMicrotasks (<anonymous>)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async commitProcessing (file:///node_modules/vite/dist/node/chunks/dep-3007b26d.js:42348:17)
at async runOptimizer (file:///node_modules/vite/dist/node/chunks/dep-3007b26d.js:42386:17)
And then a bunch of issues importing CSS files, like this one
10:45:29 AM [vite] Internal server error: Failed to resolve import "./header.css" from "node_modules/#storybook/mdx1-csf/dist/esm/stories/Header.js?v=ec48b265". Does the file exist?
Have you tried something like this?
resolve: {
alias: {
'react/jsx-runtime': 'react/jsx-runtime.js',
},
},
Source: https://github.com/vitejs/vite/issues/6215
Also:
optimizeDeps.include: ['react/jsx-runtime']
Another way can be tweaking the configuration of #vitejs/plugin-react:
import react from '#vitejs/plugin-react';
export default defineConfig({
plugins: [
react({
jsxRuntime: 'classic',
}),
]
});

Mirage/Pretender causes errors in Vitest

I'm working on migrating from Jest to Vitest (alongside CRA > Vite migration), and I think I've got everything working, except that using Mirage causes errors. Setting the vite config test environment between happy-dom and 'jsdom' both give different errors, though they appear to be related or similar or the same (just with happy-dom giving much more useful information!
My very simplified test:
import { describe, expect, it } from "vitest"
import { createServer } from "miragejs";
describe('tests', () => {
createServer({})
it('works', () => {
expect(true).toEqual(true)
})
})
happydom error
TypeError: Cannot read properties of undefined (reading 'prototype')
❯ interceptor node_modules/pretender/dist/pretender.js:1540:46
❯ new Pretender node_modules/pretender/dist/pretender.js:1638:32
❯ PretenderConfig._create node_modules/miragejs/dist/mirage-cjs.js:6398:14
❯ PretenderConfig.create node_modules/miragejs/dist/mirage-cjs.js:6259:27
❯ Server.config node_modules/miragejs/dist/mirage-cjs.js:6824:24
❯ new Server node_modules/miragejs/dist/mirage-cjs.js:6760:10
❯ Proxy.createServer node_modules/miragejs/dist/mirage-cjs.js:6725:10
❯ src/test.test.tsx:5:2
3|
4| describe('tests', () => {
5| createServer({})
| ^
6| it('works', () => {
7| expect(true).toEqual(true)
jsdom error
Error: Errors occurred while running tests. For more information, see serialized error.
❯ Object.runTests node_modules/vitest/dist/chunk-vite-node-externalize.6956d2d9.mjs:7048:17
❯ processTicksAndRejections node:internal/process/task_queues:96:5
❯ async file:/Users/jtuzman-superdraft/dev/superdraft-core-admin/NEW-vite-admin/node_modules/vitest/dist/chunk-vite-node-externalize.6956d2d9.mjs:10545:9
❯ Vitest.runFiles node_modules/vitest/dist/chunk-vite-node-externalize.6956d2d9.mjs:10558:12
❯ Vitest.start node_modules/vitest/dist/chunk-vite-node-externalize.6956d2d9.mjs:10479:5
❯ startVitest node_modules/vitest/dist/chunk-vite-node-externalize.6956d2d9.mjs:11204:5
❯ start node_modules/vitest/dist/cli.mjs:666:9
❯ CAC.run node_modules/vitest/dist/cli.mjs:662:3
⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯
Serialized Error: {
"errors": [
[Error: Internal error: Error constructor is not present on the given global object.],
],
}
vite.config.ts
/// <reference types="vitest" />
import { defineConfig } from 'vite';
import react from '#vitejs/plugin-react'
import svgrPlugin from 'vite-plugin-svgr';
import macrosPlugin from "vite-plugin-babel-macros"
import checker from 'vite-plugin-checker'
// https://vitejs.dev/config/
export default defineConfig({
test: {
globals: true,
environment: "jsdom", // or "happy-dom"
},
define: {
global: {},
},
esbuild: {
logOverride: { 'this-is-undefined-in-esm': 'silent' }
},
plugins: [
react(),
svgrPlugin({
svgrOptions: {
icon: true,
},
}),
macrosPlugin(),
checker({
typescript: true,
overlay: {
panelStyle: 'height: 100vh; max-height: unset;'
}
})
],
});
This GitHub issue appears to deal with the same question but doesn't appear to solve it.
Ran into the same thing. It's the global: {} statement. When I commented it out in my vite.config.ts file, my tests ran successfully. I haven't figured out another way to solve the global error yet that caused me to set that in the first place though.
happy-dom does not provide an implementation for XMLHttpRequest, which is used by pretenderjs. The most straightforward walk around is to put the following line at the very top of your test code, before the the vitest environment:
this.XMLHttpRequest = vi.fn()
//#vitest-environment happy-dom

yargs warning: Too many arguments provided. Expected max 1 but received 2

I have an issue with my yargs configuration:
const argv = require('yargs')
.boolean('reset', {
alias: 'rs'
})
.boolean('refreshConfig', {
alias: 'rc'
})
.option('harvest', {
alias: 'h'
})
.option('lang', {
alias: 'l',
default: 'fr'
})
.help().argv;
I executed the script as below:
$ node ./srcjobs/cli.js --refreshConfig --harvest=facebook
and I received this error:
Too many arguments provided. Expected max 1 but received 2.
Do you know why ?
Thank you for your help.
.boolean receive only 1 argument, from source code
boolean<K extends string>(key: K | ReadonlyArray<K>): Argv<T & { [key in K]: boolean | undefined }>;
Proper way
const argv = require('yargs')
.boolean('reset')
.alias('rs', 'reset')
.boolean('refreshConfig')
.alias('rc', 'refreshConfig')
.option('harvest', {
alias: 'h'
})
.option('lang', {
alias: 'l',
default: 'fr'
})
.help().argv;

How to disable webpack dev server auto reload for neutrino project?

Browser: Peruse
Type of project: SAFE network website
I need to turn it off because Peruse considers window.eval() to be a security issue and thus blocks it, which in turn stops my website from loading.
Peruse is the standard browser for Maidsafe as far as I know.
Both of my attempts to fix this have failed:
webpack.config.js
module.exports = {
devServer: {
hot: false,
inline: false
}
};
neutrinorc.js
module.exports = {
use: [
[
'#neutrinojs/vue',
{
html: {
title: 'SAFE Web App'
}
}
],
(neutrino) => {
neutrino.config.devServer
.hot(false)
.inline(false)
}
]
};
The error:
Uncaught Error: Sorry, peruse does not support window.eval().
at window.eval.global.eval (/opt/Maidsafe/Peruse/resources/app.asar/webPreload.js:9:82219)
at Object../node_modules/webpack-dev-server/client/index.js?http://localhost:5000 (http://localhost:5000/index.js:957:1)
at __webpack_require__ (http://localhost:5000/index.js:679:30)
at fn (http://localhost:5000/index.js:89:20)
at Object.0 (http://localhost:5000/index.js:1060:1)
at __webpack_require__ (http://localhost:5000/index.js:679:30)
at http://localhost:5000/index.js:725:37
at http://localhost:5000/index.js:728:10
package.json
...
"dependencies": {
"#babel/helper-module-imports": "^7.0.0-beta.44",
"vue": "^2.5.16"
},
"devDependencies": {
"#neutrinojs/vue": "^8.2.1",
"#vue/devtools": "^4.1.5",
"neutrino": "^8.2.1"
}
...
The eval() errror is not coming from webpack-dev-server.
It turns out that the the default source map mode used by #neutrinojs/web which #neutrinojs/web inherits from is cheap-module-eval-source-map and needs to be set to cheap-module-source-map.
Thus neutrinorc.js needs to be configured as such:
module.exports = {
use: [
['#neutrinojs/vue', {
// Existing options
}],
(neutrino) => {
if (process.env.NODE_ENV === 'development') {
// Override the default development source map of 'cheap-module-eval-source-map'
// to one that doesn't use `eval` (reduces incremental build performance).
neutrino.config.devtool('cheap-module-source-map');
}
}
]
};

How to avoid "TypeError: Cannot set property" error with jest and babel v7?

I have a project to be upgraded from babel v6 to babel v7. To make it work is not hard, but I met some problems in unit testing code.
For working code foo.js like below.
import foo from './bar';
export {foo};
When I try to mock it in unit testing code.
import * as Foo 'path/to/foo.js';
Foo.foo = jest.fn().mockReturnValue('whatever');
It fails with error:
TypeError: Cannot set property foo of #<Object> which has only a getter
It turns out that babel v7 do transpilation different from v6. It compiles foo.js into:
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "foo", {
enumerable: true,
get: function get() {
return _bar.default;
}
});
Since foo is defined as a getter-only property of exports, it cannot manipulate the exported foo any more.
For the time being, I just change foo.js to avoid such transpilation. I'm wondering whether this is any babel config to disable such transpilation. Any ideas?
In Babel 7, you can disable this behaviour by enabling "loose" mode in #babel/preset-env. If you only want this behaviour for your test environment, you can further scope the configuration in your babelrc/babel.config.js.
babel.config.js
module.exports = {
env: {
production: {
presets: [
[
'#babel/preset-env',
{ loose: false },
],
],
},
test: {
presets: [
[
'#babel/preset-env',
{ loose: true },
],
],
},
},
}
See loose transformation.
My suspicion that Babel use to transpile properties differently than it does now. Properties that only define a getter are expected to throw a TypeError when using "use strict", otherwise no error is given.
Example Class
class TestClass
{
constructor ()
{
this._propOne = "JUMP";
}
get propOne ()
{
return this._propOne;
}
set propOne (value)
{
this._propOne = value;
}
get propTwo ()
{
return "HOW HIGH";
}
}
const testClass = new TestClass();
console.log(customer.propOne);
customer.propOne = "10 Feet!";
console.log(customer.propOne);
customer.propTwo = "20 Feet!";
Babel 6.x Log
> JUMP
> 10 Feet!
> HOW HIGH
> HOW HIGH
Babel 7.x Log
> JUMP
> 10 Feet!
> HOW HIGH
> Uncaught TypeError: Cannot set property propTwo of #<TestCustomer> which has only a getter

Resources