Skip to content

Instantly share code, notes, and snippets.

@vikiboss
Last active October 9, 2024 09:00
Show Gist options
  • Save vikiboss/a1d77ecb833cf96e83ae14652c6ef169 to your computer and use it in GitHub Desktop.
Save vikiboss/a1d77ecb833cf96e83ae14652c6ef169 to your computer and use it in GitHub Desktop.
Install latest LTS Nodejs.js in Linux
#!/bin/bash
# 工具函数,用于打印错误信息并退出
error_exit() {
echo "$1" 1>&2
exit 1
}
# 检查命令是否存在,如果不存在则尝试安装
ensure_command() {
local cmd=$1
local install_cmd=$2
if ! command -v $cmd &>/dev/null; then
echo "未发现 $cmd, 正在安装..."
eval $install_cmd || error_exit "安装 $cmd 失败"
fi
}
# 检查并安装必要的工具
ensure_tools() {
ensure_command curl "sudo $PACKAGE_INSTALLER curl -y"
}
# 安装 Node.js LTS 版本
install_node() {
ensure_tools
# 使用 NodeSource 脚本安装 Node.js LTS
curl -fsSL https://deb.nodesource.com/setup_lts.x | sudo -E bash - || error_exit "安装 Node.js NodeSource 脚本失败"
sudo $PACKAGE_INSTALLER nodejs -y || error_exit "安装 Node.js 失败"
}
# 主函数
main() {
if [ -f /etc/os-release ]; then
. /etc/os-release
# 设置包管理器安装命令
case $ID in
ubuntu | debian | linuxmint)
PACKAGE_INSTALLER="apt-get install"
;;
fedora | centos | rhel)
PACKAGE_INSTALLER="yum install"
;;
opensuse* | sles)
PACKAGE_INSTALLER="zypper install"
;;
arch | manjaro)
PACKAGE_INSTALLER="pacman -S --noconfirm"
;;
*)
error_exit "抱歉,您的 Linux 发行版 $ID 不在支持列表中"
;;
esac
install_node
echo "Node.js 安装完成, 版本: $(node -v), npm 版本: $(npm -v)。"
else
error_exit "无法确定您的 Linux 发行版"
fi
}
# 运行主函数
main
@vikiboss
Copy link
Author

vikiboss commented Oct 9, 2024

wget -qO- https://setup-node.viki.moe | bash
curl -sSL https://setup-node.viki.moe | bash

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment