Giter Club home page Giter Club logo

nvexeca's Introduction

nvexeca logo

Node TypeScript Codecov Mastodon Medium

nvm + execa = nvexeca.

Execa improves child processes execution with a promise interface, cross-platform support, local binaries, interleaved output, and more.

nvexeca is a thin wrapper around Execa to run any file or command using any Node.js version.

Unlike nvm exec it:

  • is run programmatically
  • does not need a separate installation step for each Node version
  • can run the major release's latest minor/patch version automatically
  • does not require Bash
  • is installed as a Node module
  • works on Windows. No need to run as Administrator.

nvexeca executes a single file or command. It does not change the node nor npm global binaries. To run a specific Node.js version for an entire project or shell session, please use nvm, nvm-windows, n or nvs instead.

Hire me

Please reach out if you're looking for a Node.js API or CLI engineer (11 years of experience). Most recently I have been Netlify Build's and Netlify Plugins' technical lead for 2.5 years. I am available for full-time remote positions.

Example

import nvexeca from 'nvexeca'

const { childProcess, versionRange, version } = await nvexeca('8', 'node', [
  '--version',
])
console.log(`Node ${versionRange} (${version})`) // Node 8 (8.16.2)
const { exitCode, stdout, stderr } = await childProcess
console.log(`Exit code: ${exitCode}`) // 0
console.log(stdout) // v8.16.2

Install

npm install nvexeca

node >=18.18.0 must be installed. However the command run by nvexeca can use any Node version (providing it is compatible with it).

This package is an ES module and must be loaded using an import or import() statement, not require(). If TypeScript is used, it must be configured to output ES modules, not CommonJS.

To use this as a CLI instead, please check nve.

Usage

nvexeca(versionRange, command, args?, options?)

Executes command ...args with a specific Node.js versionRange.

Arguments

versionRange

Type: string

This can be:

command

Type: string

File or command to execute. Both global and local binaries can be executed.

Must be compatible with the specific Node versionRange. For example npm is only compatible with Node >=6.

args

Type: string[]?

Arguments to pass to the command.

Options

Type: object?

All Execa options are available. Please refer to Execa for the list of possible options.

The preferLocal option is always true.

The following options are also available.

dry

Type: boolean
Default: false

Do not execute the command. This can be used to cache the initial Node.js binary download.

progress

Type: boolean
Default: false

Whether to show a progress bar when the Node binary is downloading.

mirror

Type: string
Default: https://nodejs.org/dist

Base URL to retrieve Node binaries. Can be overridden (for example https://npmmirror.com/mirrors/node).

The following environment variables can also be used: NODE_MIRROR, NVM_NODEJS_ORG_MIRROR, N_NODE_MIRROR or NODIST_NODE_MIRROR.

fetch

Type: boolean
Default: undefined

The list of available Node.js versions is cached for one hour by default. If the fetch option is:

  • true: the cache will not be used
  • false: the cache will be used even if it's older than one hour

arch

Type: string
Default: process.arch

Node.js binary's CPU architecture. This is useful for example when you're on x64 but would like to run Node.js x32.

All the values from process.arch are allowed except mips and mipsel.

cwd

Type: string | URL
Default: process.cwd()

Current working directory of the child process.

When using the local alias, this also starts looking for a Node.js version file from this directory.

Return value

Type: Promise<object>

Promise resolved after the Node.js version has been cached locally (if it has not been cached yet).

If you want to wait for the command to complete as well, you should await the returned childProcess.

const { childProcess } = await nvexeca('8', 'node', ['--version'])
const { exitCode, stdout, stderr } = await childProcess

childProcess

Type: ResultPromise?

childProcess instance. It is also a Promise resolving or rejecting with a Result. The Promise should be awaited if you want to wait for the process to complete.

This is undefined when the dry option is true.

versionRange

Type: string

Node.js version passed as input, such as "v10".

version

Type: string

Normalized Node.js version. For example if "v10" was passed as input, version will be "10.17.0".

command

Type: string

File or command that was executed.

args

Type: string[]

Arguments that were passed to the command.

execaOptions

Type: object

Options that were passed to Execa.

Initial download

The first time nvexeca is run with a new VERSION, the Node binary is downloaded under the hood. This initially takes few seconds. However subsequent runs are almost instantaneous.

Native modules

If your code is using native modules, nvexeca works providing:

  • they are built with N-API
  • the target Node.js version is >=8.12.0 (since N-API was not available or stable before that)

Otherwise the following error message is shown: Error: The module was compiled against a different Node.js version.

See also

Support

For any question, don't hesitate to submit an issue on GitHub.

Everyone is welcome regardless of personal background. We enforce a Code of conduct in order to promote a positive and inclusive environment.

Contributing

This project was made with ❤️. The simplest way to give back is by starring and sharing it online.

If the documentation is unclear or has a typo, please click on the page's Edit button (pencil icon) and suggest a correction.

If you would like to help us fix a bug or add a new feature, please check our guidelines. Pull requests are welcome!


ehmicky

💻 🎨 🤔 📖

Nicolas Goudry

📖

Pedro Augusto de Paula Barbosa

💬

nvexeca's People

Contributors

allcontributors[bot] avatar dependabot[bot] avatar ehmicky avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

nvexeca's Issues

nvexeca is hanging

Describe the bug

The promise returned by called nvexeca never seems to resolve (or rather, seems to have stopped...).

Steps to reproduce

#!/usr/bin/env node

const nvexeca = require('nvexeca')

// force process to stay alive
const timer = setTimeout(() => {
	console.log('time is up')
}, 3000)

const p = nvexeca('8', 'echo', ['hello'], { stdio: 'inherit', progress: true })
	.then(result => {
		console.log('then', result)
	})
	.catch(result => {
		console.log('catch', result)
	})
	.finally(result => {
		console.log('finally', result)
		clearTimeout(timer)
	})

console.log('p', p)

Results in the following:

image

Expected behavior

If I try running this with plain execa, like so:

#!/usr/bin/env node

const execa = require('execa')

// force process to stay alive
const timer = setTimeout(() => {
	console.log('time is up')
}, 3000)

const p = execa('echo', ['hello'], { stdio: 'inherit' })
	.then(result => {
		console.log('then', result)
	})
	.catch(result => {
		console.log('catch', result)
	})
	.finally(result => {
		console.log('finally', result)
		clearTimeout(timer)
	})

console.log('p', p)

you get the following output:

image

which makes sense.

Configuration

I have had it working, and deleted ~/Library/Caches/nve to trigger a new download of node, and now it's not working. I'm not sure if it stopped straight away or what was different when it did work, sorry! Just incase that helps...

Environment

Enter the following command in a terminal and copy/paste its output:

❯ npx envinfo --system --binaries --browsers --npmPackages nvexeca

  System:
    OS: macOS 10.15.3
    CPU: (16) x64 Intel(R) Core(TM) i9-9900K CPU @ 3.60GHz
    Memory: 30.67 GB / 64.00 GB
    Shell: 5.7.1 - /bin/zsh
  Binaries:
    Node: 13.10.1 - ~/.nvm/versions/node/v13.10.1/bin/node
    Yarn: 1.21.0 - ~/Dev/oh/node_modules/.bin/yarn
    npm: 6.13.7 - ~/.nvm/versions/node/v13.10.1/bin/npm
  Browsers:
    Chrome: 80.0.3987.132
    Firefox: 74.0
    Firefox Developer Edition: 69.0
    Safari: 13.0.5
  npmPackages:
    nvexeca: 2.1.1 => 2.1.1 

Am I doing something silly?

Add synchronous execution support

Which problem is this feature request solving?

I need to wait for a command to close before continuing executing my code.

I made an easy and clear test to show what is going on:

parent.mjs

import nvexeca from 'nvexeca'

console.log('parent: going to wake up child...')

await nvexeca('6', 'node', ['./child.js'], { stdout: 'inherit' })

console.log('parent: child is up!')

child.js

console.log('child: ZzZzZzZz')

setTimeout(() => {
    console.log('child: I’m up!')
}, 5000)

Actual output:

parent: going to wake up child...
parent: child is up!
child: ZzZzZzZz
child: I’m up!

Expected output with synchronous execution:

parent: going to wake up child...
child: ZzZzZzZz
child: I’m up!
parent: child is up!

Describe the solution you'd like

Maybe expose a sync function that calls execa’s sync method?

Actually, this is working as expected with execa:

await execa.sync('node', ['./child.js'], { stdout: 'inherit' })

Describe alternatives you've considered

I thought about watching over childProcess.exitCode to be updated from null to subprocess exit code. But that seems tricky and hack-ish... I think it would involve some Observable maybe? I did not dig into this solution/workaround yet.

Can you submit a pull request?

Maybe I can try to dig into sources to add this feature over next weekend, but can’t make any promises!

Support npm commands with selected node version shipped npm

Which problem is this feature request solving?

I’d like to run an npm command that would use npm version shipped with selected node version.

Describe the solution you'd like

From what I understand of your code, I think it should be in get-node project, src/download.js’s download function should return an object containing nodePath but also npmPath.

Download feature should not strip away bin/npm, bin/npx and lib folders from downloaded archive.

Also, in this project, src/spawn.js’s getCommand function should add a new if testing if command is npm and use newly created npmPath to run command through execa.

I’m probably missing some things around, but you should get the idea.

Describe alternatives you've considered

Use currently installed npm through execa, but does require user to have node/npm installed.

EDIT: that’s one “small” problem, but a bigger problem is if npm commands run node against an older/newer version than the one installed. Same for tools ran by npm that expects a given node version.

Can you submit a pull request?

Maybeee. I guess you would be far more efficient than me on this, as it requires to update several project/dependencies.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.