How to use source maps in node js? - node.js

I stareted my node app with node index.js and got the following message:
(node:10128) UnhandledPromiseRejectionWarning: TypeError: e.reduce is not a function
at Module.te (C:\Projects\myproject\node_modules\tronweb\dist\TronWeb.node.js:1:9236)
Now I'm interessted in whats happening. I've seen that there are mapping files TronWeb.node.js.map in the tronweb\dist directory. I started again using --inspect and opened the chrome dev tools. But in the console I see exactly the same message.

In Node v12.12.0+ sourcemaps are supported natively. Pass --enable-source-maps flag to enable them.
One caveat in Node v12.12.0 is that Error.prepareStackTrace will no longer be called when source maps are enabled. This was fixed in v12.16+.

You can use https://www.npmjs.com/package/source-map-support
$ npm install source-map-support --save-dev
Then change your run command in package.json to:
node -r source-map-support/register index.js
(Note that you should have an index.map.js next to index.js)

Related

Cannot run Jest in WebStorm

I am getting an error message:
"C:\Program Files\nodejs\node.exe" C:\Users\keechan\Desktop\NodeJS\my-module\tests\sample.test.js
ReferenceError: describe is not defined
This issue only happens when I run via Run (ctrl+shift+F10).
When I run via the Debug Configuration I created, it works okay.
But considering if I have many test.js files and I want to be able to run each individual test suite, I do not want to have to make a debug configuration for each one of them.
I already tried:
installing #types/jest library under settings (Languages & Frameworks > JavaScript > Libraries)
added #types/jest as well as jest in my package.json
Also, I noticed that it is calling node.exe in:
"C:\Program Files\nodejs\node.exe" C:\Users\keechan\Desktop\NodeJS\my-module\tests\sample.test.js
Maybe this is the reason why? So how do I change it to use jest?
Thank you so much!
You are not running Jest, you run your spec file by passing it directly to Node.js using Node.js run configuration. Make sure to use Jest run configuration to start your spec

browserify will not compile express js

I wrote a very basic express.js app. Then tried to make it one .js file. Browserify compiled the whole thing to a one file. But browserify-compiled code didn't work. As far as I know, browserify just replaces require statements with module codes. Error is:
C:\Users\HP\n\express\app.js:27025
__proto__: http.IncomingMessage.prototype
^
TypeError: Cannot read property 'prototype' of undefined
at Object.__dirname.173.accepts (C:\Users\HP\n\express\app.js:27025:34)
at s (C:\Users\HP\n\express\app.js:1:316)
at C:\Users\HP\n\express\app.js:1:367
at Object.__dirname.170../application (C:\Users\HP\n\express\app.js:26823:11)
at s (C:\Users\HP\n\express\app.js:1:316)
at C:\Users\HP\n\express\app.js:1:367
at Object.__dirname.168../lib/express (C:\Users\HP\n\express\app.js:26154:18)
at s (C:\Users\HP\n\express\app.js:1:316)
at C:\Users\HP\n\express\app.js:1:367
at Object.__dirname.153.express (C:\Users\HP\n\express\app.js:24010:15)
Browserify is designed specifically to package code for a browser.
Node.js supports a number of modules that a browser doesn't which have to be emulated by builtins. These modules will be replaced by a browser-specific shim. Some only supply a subset of the Node API that makes sense to have in a browser.
So you are running an app that has converted all the Node.js modules to support running what it can in a browser, back in Node where the modules are available but are no longer being used.
Try rollup or you could possibly configure babel to work like you need
I had this very same issue but like you said the compile code should work on server side. I solved it from this link:
https://www.linkedin.com/pulse/bundling-nodemodules-your-nodejs-app-one-single-file-xuan-son-nguyen/
Use browserify for bundling and terser for minifying. Starting by installing them globally:
npm install -g browserify
npm install -g terser
Next, we have to add a build script to package.json
...
"scripts": {
...
"build": "browserify --node --ignore-missing index.js | terser > bundle.js"
}
...
Each time you want to promote to production, you have to make a new bundle:
npm run build
A new file called "bundle.js" will be created.
Let there be peace, and there was peace. Happy coding.

How to run TypeScript files from command line?

I'm having a surprisingly hard time finding an answer to this. With plain Node.JS, you can run any js file with node path/to/file.js, with CoffeeScript it's coffee hello.coffee and ES6 has babel-node hello.js. How do I do the same with Typescript?
My project has a tsconfig.json which is used by Webpack/ts-loader to build a nice little bundle for the browser. I have a need for a build step run from the console before that, though, that would use some of the .ts files used in the project to generate a schema, but I can't seem to be able to run a single Typescript file without compiling the whole project.
How do I do the same with Typescript
You can leave tsc running in watch mode using tsc -w -p . and it will generate .js files for you in a live fashion, so you can run node foo.js like normal
TS Node
There is ts-node : https://github.com/TypeStrong/ts-node that will compile the code on the fly and run it through node 🌹
npx ts-node src/foo.ts
Run the below commands and install the required packages globally:
npm install -g ts-node typescript '#types/node'
Now run the following command to execute a typescript file:
ts-node typescript-file.ts
We have following steps:
First you need to install typescript
npm install -g typescript
Create one file helloworld.ts
function hello(person){
return "Hello, " + person;
}
let user = "Aamod Tiwari";
const result = hello(user);
console.log("Result", result)
Open command prompt and type the following command
tsc helloworld.ts
Again run the command
node helloworld.js
Result will display on console
To add to #Aamod answer above, If you want to use one command line to compile and run your code, you can use the following:
Windows:
tsc main.ts | node main.js
Linux / macOS:
tsc main.ts && node main.js
Edit: May 2022
ts-node now has an --esm flag use it.
Old Answer:
None of the other answers discuss how to run a TypeScript script that uses modules, and especially modern ES Modules.
First off, ts-node doesn't work in that scenario, as of March 2020. So we'll settle for tsc followed by node.
Second, TypeScript still can't output .mjs files. So we'll settle for .js files and "type": "module" in package.json.
Third, you want clean import lines, without specifying the .js extension (which would be confusing in .ts files):
import { Lib } from './Lib';
Well, that's non-trivial. Node requires specifying extensions on imports, unless you use the experimental-specifier-resolution=node flag. In this case, it would enable Node to look for Lib.js or Lib/index.js when you only specify ./Lib on the import line.
Fourth, there's still a snag: if you have a different main filename than index.js in your package, Node won't find it.
Transpiling makes things a lot messier than running vanilla Node.
Here's a sample repo with a modern TypeScript project structure, generating ES Module code.
I created #digitak/esrun, a thin wrapper around esbuild and that executes a TypeScript file almost instantly. esrun was made because I was disappointed with ts-node: too slow, and just didn't work most of the time.
Advantages of esrun over ts-node include:
very fast (uses esbuild),
can import ESM as well as CJS (just use the libraries of your choice and esrun will work out of the box),
there is an included watch mode, run your script with the --watch option and any change to your entry file or any of its dependencies will re-trigger the result
you can use esrun in inspect mode to use the DevTools console instead of your terminal console.
After installing, just run:
npx #digitak/esrun file.ts
Just helpful information - here is newest TypeScript / JavaScript runtime Deno.
It was created by the creator of node Ryan Dahl, based on what he would do differently if he could start fresh.
You can also try tsx.
tsx is a CLI command (alternative to node) for seamlessly running TypeScript, its build upon esbuild so its very fast.
https://github.com/esbuild-kit/tsx
Example:
npx tsx ./script.ts
As of May 2022 ts-node does support es modules
npx ts-node --esm file.ts
you will likely need to add "type": "module", to your package.json. And some of the imports might be wonky unless you turn on experimental-specifier-resolution=node
npmjs.com/package/ts-node#commonjs-vs-native-ecmascript-modules
For linux / mac you can add the ts-node-script shebang.
Install typescript / ts-node globally (see 1 below for non global install):
npm install ts-node typescript --save-dev --global
Add this as the first line in your .ts file:
#!/usr/bin/env ts-node-script
Then make the file executable:
$ chmod +x ./your-file.ts
You can then run the file directly from the command line:
$ ./your-file.ts
Notes:
1 For non global install you can install local to your project
npm install ts-node typescript --save-dev
and add the relative path to the shebang script eg:
#!/usr/bin/env ./node_modules/.bin/ts-node-script
2 Support for shebangs was officially added in ts-node v8.9.0.
Like Zeeshan Ahmad's answer, I also think ts-node is the way to go. I would also add a shebang and make it executable, so you can just run it directly.
Install typescript and ts-node globally:
npm install -g ts-node typescript
or
yarn global add ts-node typescript
Create a file hello with this content:
#!/usr/bin/env ts-node-script
import * as os from 'os'
function hello(name: string) {
return 'Hello, ' + name
}
const user = os.userInfo().username
console.log(`Result: ${hello(user)}`)
As you can see, line one has the shebang for ts-node
Run directly by just executing the file
$ ./hello
Result: Hello, root
Some notes:
This does not seem to work with ES modules, as Dan Dascalescu has pointed out.
See this issue discussing the best way to make a command line script with package linking, provided by Kaspar Etter. I have improved the shebang accordingly
Update 2020-04-06: Some changes after great input in the comments: Update shebang to use ts-node-script instead of ts-node, link to issues in ts-node.
Write yourself a simple bash wrapper may helps.
#!/bin/bash
npx tsc $1 && node ${1%%.ts}
For environments such as Webstorm where the node command cannot be changed to ts-node or npx:
npm install ts-node typescript (Install dependencies)
node --require ts-node/register src/foo.ts (Add --require ts-node/register to "Node parameters")
This answer may be premature, but deno supports running both TS and JS out of the box.
Based on your development environment, moving to Deno (and learning about it) might be too much, but hopefully this answer helps someone in the future.
Just in case anyone is insane like me and wants to just run typescript script as though it was a .js script, you can try this. I've written a hacky script that appears to execute the .ts script using node.
#!/usr/bin/env bash
NODEPATH="$HOME/.nvm/versions/node/v8.11.3/bin" # set path to your node/tsc
export TSC="$NODEPATH/tsc"
export NODE="$NODEPATH/node"
TSCFILE=$1 # only parameter is the name of the ts file you created.
function show_usage() {
echo "ts2node [ts file]"
exit 0
}
if [ "$TSCFILE" == "" ]
then
show_usage;
fi
JSFILE="$(echo $TSCFILE|cut -d"." -f 1).js"
$TSC $TSCFILE && $NODE $JSFILE
You can do this or write your own but essentially, it creates the .js file and then uses node to run it like so:
# tsrun myscript.ts
Simple. Just make sure your script only has one "." else you'll need to change your JSFILE in a different way than what I've shown.
Install ts-node node module globally.
Create node runtime configuration (for IDE) or use node in command line to run below file js file (The path is for windows, but you can do it for linux as well)
~\AppData\Roaming\npm\node_modules\ts-node\dist\bin.js
Give your ts file path as a command line argument.
Run Or Debug as you like.
Create your TypeScript file (ex. app.ts)
npm i -D typescript ts-node -> to install the dev dependencies local
npx nodemon app.ts
Using nodemon, automatically recompile app.ts every time you change the file
Here is the command
tsc index.ts --outDir .temp && node .temp/index.js && rm -rf .temp
<<<<<<<<< Compile >>>>>>>>> <<<<<<< Run >>>>>>> << Clean >>
There is also an option to run code directly from the CLI, not the *.ts file itself.
It's perfectly described in the ts-node manual.
As a first step, install ts-node globally via npm, yarn, or whatever you like.
...and now just use ts-node -e 'console.log("Hello, world!")' (you may also add the -p flag for printing code)
This little command is perfect for checking, does everything installed fine. And for finding some other error, relevant with tsconfig.json options.
We can run it using nodemon as well
nodemon ./filepath/filename.ts
This question was posted in 2015. In 2018, node recognizes both .js and .ts. So, running node file.ts will also run.

How can I debug a Sails.js app with node-inspector?

In order to debug with node-inspector I need to start my app with the node --debug command. Up to this point I have only used sails lift to start my Sails.js app, so I am unsure of how to start my app using the normal node command.
So you can actually launch a sails project with node app.js --debug if you have sails installed in your project, rather than only system-wide. Go to your project's root directory and run npm install. Sails should already be in your package.json and thus should install to your project directory.
As of Sails v0.10.x, you can do sails debug instead of sails lift.
sails inspect since Sails v1.0
As of sails v1.0, sails debug is deprecated for newer Node.js, and you should instead use sails inspect.
This is documented at: https://sailsjs.com/documentation/reference/command-line-interface/sails-inspect and is presumably done to match the newer node --inspect interface.
Have you tried using node-webkit to run your node.js apps? This is what we use at work to debug our node.js server applications. It is quite useful runtime based on chromium which you can use to inspect your code using familiar breakpoints, stack traces, variable inspection and such without having to rely on node-inspector (which I find hard to use to be honest).
What you do is instead of using console command 'node you-app.js' you set the node-webkit to launch your app, run the webkit then open its console (which is the same as console in Chrome browser) and from there you can open your source files and start debugging like any other client side JavaScript code.
node inspect
You can also use the command line debugger with:
node inspect app.js
This stops at the beginning, so do a continue:
c
And now, when your code with a statement:
debugger
gets executed, you fall into the Node CLI debugger as usual.
Tested on Sail v1.1, Node v10.15.1, Ubuntu 18.10.
nodemon --inspect and nodemon inspect
You can use those to inspect when using nodemon, which automatically reloads the app on file save: Auto reloading a Sails.js app on code changes?
Those options are analogous to node inspect and node --inspect: node inspect works with debugger statements, and node --inspect works with the Chrome debugger.
Especially useful with the "Open dedicated DevTools for Node" feature: Can I get node --inspect to open Chrome automatically
nodemon inspect is a bit annoying as it requires a continue everytime you make any app changes and nodemon restarts the server. TODO find a way around it.

Node.JS Express Authentication App Creation TypeError

I'm working through a tutorial on Node.js that begins with a simple authentication program. This is the second time I'm doing this tutorial, and the first time, everything worked fine. However, upon uninstalling node and starting from scratch (installing node.js and express via npm), the instantiation of authentication errors out as below.
program.confirm('destination is not empty, continue? ', function(ok){
^
TypeError: Object #<Command> has no method 'confirm'
at C:\Users\Kyle\AppData\Roaming\npm\node_modules\express\bin\express:251:15
at C:\Users\Kyle\AppData\Roaming\npm\node_modules\express\bin\express:382:5
at Object.oncomplete (fs.js:107:15)
I'm on a windows machine, running Node.js v0.10.20 and express v3.4.1.
Is this a result of the inconsistent -g flag install referenced here?
EDIT: Express initializes apps fine in other directories, even those with the subdirectory Node.js. The path to this problem folder is C:\dev\Node.js\ ...any idea why Express refuses to initialize something in this folder?
Try:
Remove your directory
"C:\Users\Kyle\AppData\Roaming\npm\node_modules\express\node_modules\commander".
Install node module "commander 1.3.2" globally.
Command line: $ npm install -g commander#1.3.2
Run "express" again.
It seems to be the problem referred to the new version(2.0.0) of the commander module.
It works on my mac.
Good luck~
I had the same problem. Rather than fix the problem, you can fix the source of the problem (not specifying an empty directory). In my case I was specifying an empty directory, but it was associating that with the previous switch.
I had to change:
node_modules/.bin/express -s -e -c ./server
To:
node_modules/.bin/express -s -e -c css ./server
Otherwise it thought the server path was the type of css to use and was setting the code path to '.'

Resources