How to enable debug for node modules? - node.js

Having started to work on node.js recently, I am trying to use rename package. Successfully installed (npm install rename) package and sample code (residing in file test.js) is pasted below:
console.log('Starting to rename');
var rename = require('rename');
rename('a.js', 'b.js');
console.log('Rename done');
The file a.js resides in the same directory as test.js. The console shows the two debug messages correctly, but the file a.js is not renamed.
How can I enable debug on rename module (or for that matter any node module), so that I can debug it additional log messages?
Note: Other packages like find, mkdirp, etc are working fine.

You can enable debug by doing a DEBUG=* node app.js or passign env variable DEBUG with wildcard * . It would enable debug for all modules, provided the module you wish to debug is actually using debug.
Hardcore way of doing is to make local changes in the module.

Related

Ignore filename extension for child_process fork using node-dev and Typescript

I have a project written in Typescript, and I'm using node-dev alongside ts-node in my local enviroment for development. I'm using child_process's fork method to instantiate a subprocess, like so:
fork(path.join(__dirname, './worker.ts'));
This works fine, and I can even set breakpoints in VS Code for the worker.
The problem is that when building (transpiling) my project, a MODULE_NOT_FOUND exception is thrown because worker.ts turned into worker.js. Initially, mi idea was to omit the file extension when forking (fork(path.join(__dirname, './worker'));), but if I do so, when running the project with node-dev, it throws a MODULE_NOT_FOUND because it can't resolve the file if the extension is not present.
Is there any workaround for this? Maybe an extra configuration option for node-dev?
I'm on Windows 10 using node v12.22.1
A simple solution I suggest would be to read in the current file type. The compiled files should end with ".js" while the source files end with ".ts". Using the path.extname methode in combination with __filename you can easily extract that file extension and simply concat it to your file name.
fork(path.join(__dirname, './worker' + path.extname(__filename)));

how to require a .js file in node repl

so i usually use ruby irb, and I can pull .rb files I wrote into the console environment by running
load './script.rb'
and then all of the functions I wrote in script.rb will be available.
I cannot figure out for the life of me how to do this in the node "console" environment!
You can load JavaScript files using the require function. The following example assume that the Node.js process was started at the directory where your file is located.
require('./script.js');
This will execute the contents of the file.
If you have exported functions or objects, you can assign them to a variable and use them later.
const myFunction = require('./script.js').myFunction;
myFunction();
Like many other development frameworks/languages, Node has a Modules/Package System which, is a CommonJS variant. To load a Module use require(). The usage of require() is the same when running JavaScript files or running in the REPL.
You can require Node Core Modules, NPM Installed Packages or your own local modules. When loading NPM Packages specified in a package.json or a local module, Node will load them from the Current Working Directory(CWD), you can check this using process.cwd(). The CWD will be set to the absolute path of the directory you launched the REPL from.
You can launch the REPL via running node in your CLI and require your packages like below.
// Core Package
const os = require('os')`
console.log(os)
// NPM Package
const moment = require('moment')
console.log(moment)
// Local Package
const myPackage = require('./myPackage')
console.log(myPackage)
You can also pre-require module(s) using the -r flag when running node. The below will launch the Node REPL with the os package preloaded. You can then access the os package using the variable os
node -r os
console.log(os)
In the future, Node may also support ECMAScript Modules (ie. import). You can read more detailed info about that in the Enhancement Proposal.

How to use the "debug" module with typescript

I have an NTVS (Node Tools for Visual Studio) project with Typescript.
The following statement doesn't compile:
import debug = require('debug')('MyApp');
The syntax error being
(TS) ';' expected
between the the two parenthesis ')('
Is it possible to use "debug" with TypeScript?
From the README, debug module is exporting a function that decorates console.error with your module name (MyApp). I'm guessing there are other ways, but I use:
import Debug from "debug";
const debug = Debug("MyApp");
// then to use
debug("Something happened");
And to print everything to the console, run your app with...
$ DEBUG=* node MyApp.js
The answers here did not work for me with more recent versions of Typescript. Here's how I got it working with proper import syntax in Typescript ^3.5.3:
Install Debug package and Typescript types for Debug (types only needed for dev)
npm install --save debug
npm install --save-dev #types/debug
Then in .ts files:
import Debug from "debug";
const debug = Debug("AppName");
Hope this helps someone else!
Remember that TypeScript is a super-set of javascript, so you can still also do this one-liner:
const debug = require('debug')('my-app:my-module');
Typescript seems to conclude that the debug constant here is of type 'any', and you lose all type safety, but with a package as simple as debug is, I think you will be OK...
Personally, I think 2 lines to instantiate debugging in every module is 1 line too many, so I continue to use this one-liner in my .ts files.
P.S. I like to use module tags so I can enable logging in just certain modules with DEBUG=my-app:my-module,my-app:some-other-module ts-node my-app or all my modules with DEBUG=my-app:* ...
The solution to debug not showing any logs in typescript is due to the reason that debug relies on the environment variables to decide how to show the logs
Solution
Make sure you have installed dotenv and its type definition file
npm install dotenv && npm install -D #types/dotenv
Then create a .env file at the root folder of your project add and this environment variable:
DEBUG = *
finally at the index file of your application. Configure dotenv to load the environment variables before any other task is run.
Its very important dotenv configuration is done at the top of the index file, before any other lines of code.
Add this two lines of code
import dotenv from "dotenv";
dotenv.config();
This should load the DEBUG environment variable required by debug to show output on the standard input.
Remember if you want to view logs defined in your files only and not other logs from other modules. Its better you define your application name as the namespace. That way you can filter the logs by the environment variable described above i.e.
const debug = debug("applicationName:other-more-information");
Then to view your debug logs alone just change the DEBUG varibale from * to applicationName:*
DEBUG = applicationName:*
For unix based os users you can try exporting this variable to enviroment variables directly (Though i have not tested this solution) export DEBUG=* - This method will only work for all process started on this shell

Browserify - JsSip

I have a new project where I'm using browserify to convert node modules into an sdk that can run inside the browser.
I'm requiring a number of other npm packages like:
var log4js = require('log4js');
That run fine and give me no problems in the browser, however JsSip just will not cooperate. When I do
var JsSIP = require('jssip');
I get
plivowebsdk.js:2 Uncaught Error: Cannot find module '../../package.json'
Looking through the code, it's obvious when it makes this call
var pkg = require('../../package.json');
is where it bombs out. Clearly it cannot find the package.json file, which it uses to pull out version information. I know JsSip is actually built with browersify itself (or used to be) so that it can run in either node or a browser. Is this causing a conflict?
Still sort of new to browserify, is their a configuration option or transformation I can perform to get around this?
Turned out the be browserify errors, re did the build process using the gulp recipes for browersify and works as expected.

node jitsu cannot find local modules

I have an application successfully working locally so I know the code works. However when I go to deploy to node jitsu I get an error that it cannot find a local module. Here is what I have:
File Setup:
/index.js
/config/config.js
index.js
var cfg = require('./config/config.js');
When trying to deploy node jitsu is giving me an error:
Error: Cannot find module './config/config.js'
Since all this code works locally I do not believe this is a coding issue. I am under the impression that local modules do not need to be included in package.json but perhaps they do for node jitsu? I read their documentation but cannot find anything special for local modules.
Thanks!
Local modules like this should work properly.. so long as you don't have it in .gitignore or .npmignore.
Modules in the node_modules directory require that you add it to the bundledDependencies array in your package.json file.
An easy way to check for whether the file is included in your deploy is to run tar -tf $(npm pack).
I had this exact same error on deploy, but caused by a different root cause. In case anybody stumbles into the same problem:
File Setup:
/public/Data/TargetData.js
app.js require statement:
var target = require('./public/data/TargetData.js');
My local Mac OSX environment allowed the capitalization difference of /data/ vs. /Data/ - the Nodejitsu server did not.

Resources