Ubuntu系统默认的Node.js版本可能过旧,无法满足现代JavaScript项目(如使用ES6+语法、新API或第三方库)的需求。需通过以下方式管理Node.js版本:
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.1/install.sh | bash,安装后重新加载终端(source ~/.bashrc),再通过nvm install <版本号>(如nvm install 18)安装指定版本,用nvm use <版本号>切换版本。curl -fsSL https://deb.nodesource.com/setup_18.x | sudo -E bash -,然后sudo apt-get install -y nodejs,安装后验证版本(node -v)。build-essential、python3等编译依赖(用于安装含原生模块的npm包),命令:sudo apt update && sudo apt install -y build-essential python3。npm install安装package.json中定义的所有依赖。若依赖安装缓慢,可切换npm镜像源(如淘宝镜像):npm config set registry https://registry.npmmirror.com。chmod +x script.js,然后通过./script.js运行;sudo运行npm命令(可能导致全局安装的包权限混乱)。若开发Electron应用(如桌面客户端),需额外解决桌面环境适配问题:
const { app } = require('electron');
function supportsWayland() {
try {
const session = require('child_process').execSync('loginctl show-session $(loginctl | grep $(whoami) | head -n1 | awk "{print $1}") -p Active --value', { encoding: 'utf8' }).trim();
const xdg = process.env.XDG_SESSION_TYPE;
return xdg === 'wayland' && session === 'yes';
} catch {
return false;
}
}
if (supportsWayland()) {
app.commandLine.appendSwitch('enable-features', 'UseOzonePlatform');
app.commandLine.appendSwitch('ozone-platform', 'wayland');
}
node-notifier库封装通知逻辑,自动适配后端:const notifier = require('node-notifier');
notifier.notify({
title: '新消息',
message: '您有一条未读消息',
icon: path.join(__dirname, 'assets/icon.png'),
sound: true,
wait: true // 等待用户点击后回调
});
export http_proxy="http://127.0.0.1:7890"、export https_proxy="http://127.0.0.1:7890",加速依赖下载。node inspect your_script.js,或在代码中添加debugger语句,然后用Chrome访问chrome://inspect连接调试。以上方法覆盖了Ubuntu下JavaScript开发中常见的兼容性问题,可根据具体场景选择对应方案。