Skip to main content

13 posts tagged with "Node.js"

View All Tags

Don't use --prefer-offline

If you set --prefer-offline to true in npm, naively thinking (like I did) that this will speed up your npm installs, you will be disappointed (like I was). Annoyingly, this setting causes npm to also cache which packages and versions don't exist. Thus, updating a dependency to a newly published version causes npm to think it doesn't exist and, instead of doing anything about it, npm will simply error out.

Running a TypeScript worker in Node.js

It's really hard to get new Worker() from node:worker_threads to work when running code via tsx. I finally got an example working. Here's how to do it:

import {Worker} from 'node:worker_threads';

const workerPath = import.meta.resolve('./sample-worker.js');
const worker = import.meta.filename.endsWith('.ts')
? new Worker(
`import('tsx/esm/api').then(({ register }) => { register(); import('${workerPath}') })`,
{
eval: true,
},
)
: new Worker(workerPath);

ESM scripts can detect when they're run directly

CJS Node.js scripts have always been able to detect if they're running directly through the CLI or imported from another JS script through various means (the most recent being require.main === module).

However, ESM scripts have not been so lucky. For years the answer to this in ESM has simply been no.

Now it's in Node.js v24! You use it like this:

if (import.meta.main) {
// executed from CLI
} else {
// imported into another JS module
}

pm2 Quick Start

I couldn't find a single consolidated place that explains how to setup pm2 from scratch (assuming you've already installed Node.js), and their own "quick start" didn't help. I was finally able to piece together how to get it working.

ESM vs CJS

There are currently two main module formats in the JavaScript ecosystem: ECMAScript Modules (ESM) and CommonJS (CJS). CJS was first, but ESM is now the JavaScript standard and is the future. The main difference between the two is how they import files.

Making Your Terminal Awesome

The tools we use as developers make us more effective (or at least hopefully faster) developers. So why not spend some time to make one of the most common dev tools much more useful? Here's a way to give any terminal app a personalized and awesome experience (fwiw I use the default app included with macOS). Features covered will be the following:

  • a super informative and customizable prompt
  • per-directory prompt customization
  • automatic switching of Node.js versions (easily extended to any run-time)
  • better auto complete and history
  • optional "command done" chime