UNPKG

get-node

Version:

Download a specific version of Node.js

115 lines (71 loc) 1.93 kB
import{rm}from"node:fs/promises"; import{join}from"node:path"; import{platform}from"node:process"; import{moveFile}from"move-file"; import{pathExists}from"path-exists"; import{tmpName}from"tmp-promise"; import{getArch}from"./arch.js"; import{downloadRuntime}from"./archive/main.js"; export const download=async({version,output,arch,fetchOpts})=>{ const archA=getArch(arch); const nodePath=join(output,version,archA,NODE_FILENAME); if(await pathExists(nodePath)){ return nodePath } await downloadFile({version,nodePath,arch:archA,fetchOpts}); return nodePath }; const NODE_FILENAME=platform==="win32"?"node.exe":"bin/node"; const downloadFile=async({version,nodePath,arch,fetchOpts})=>{ const tmpFile=await tmpName({prefix:`get-node-${version}-${arch}`}); try{ await tmpDownload({version,tmpFile,arch,fetchOpts}); await moveTmpFile(tmpFile,nodePath) }finally{ await cleanTmpFile(tmpFile) } }; const tmpDownload=async({version,tmpFile,arch,fetchOpts})=>{ const checksumError=await safeDownload({ version, tmpFile, arch, fetchOpts }); if(checksumError!==undefined){ throw new Error(await checksumError) } }; const safeDownload=async({version,tmpFile,arch,fetchOpts})=>{ try{ return await downloadRuntime({version,tmpFile,arch,fetchOpts}) }catch(error){ throw new Error( getDownloadError({message:error.message,version,arch,fetchOpts}) ) } }; const getDownloadError=({ message, version, arch, fetchOpts:{mirror} })=>{ if(message.includes("getaddrinfo")){ return`Could not connect to ${mirror}` } if(message.includes("404")){ return`No Node.js binaries available for ${version} on ${platform} ${arch}` } /* c8 ignore next */ return`Could not download Node.js ${version}: ${message}` }; const moveTmpFile=async(tmpFile,nodePath)=>{ if(await pathExists(nodePath)){ return } await moveFile(tmpFile,nodePath) }; const cleanTmpFile=async(tmpFile)=>{ await rm(tmpFile,{force:true,recursive:true}) };