Ubuntu 16.04下Node.js脚本控制台运行报错问题求助
Hey there! Let's break down why your hello.js script throws an error in the console even though it loads fine in the browser, plus how to fix each common issue:
1. You're Using the Wrong Command to Run the Script
Browser access works because your Node.js server is already running (from your deployment setup), but running the script directly in the console requires explicit Node.js invocation.
- Fix: First navigate to the script's directory:
Then run it with the Node executable:cd /var/www/html/nodejs/
If you want to run it like a standalone app, add a shebang line at the very top ofnode hello.jshello.js:
Grant execute permissions, then run it directly:#!/usr/bin/env node // rest of your hello.js codechmod +x hello.js ./hello.js
2. Port 8080 Is Already Occupied
If the Node server from your browser-accessible setup is still running, trying to launch the script again will throw an EADDRINUSE error—port 8080 can't be used by two processes at once.
- Fix: Kill the existing Node process first:
Or kill all Node processes (use cautiously if you have other Node apps running):# Target the process using port 8080 specifically lsof -ti:8080 | xargs kill -9
Then run your script again.pkill node
3. Permission Restrictions on the Script/Directory
Apache runs under the www-data user, which has access to /var/www/html/nodejs/, but your regular user account might lack read or execute permissions for the script.
Fix: Check current permissions with:
ls -l /var/www/html/nodejs/hello.jsIf the owner is
rootorwww-data, transfer ownership to your user:sudo chown your_username:your_username /var/www/html/nodejs/hello.js(Replace
your_usernamewith your actual Ubuntu username.)Ensure your user can read the script:
sudo chmod 644 /var/www/html/nodejs/hello.js
4. Missing npm Dependencies
If hello.js uses external packages, dependencies might be installed in a location accessible to Apache but not your regular user, or you're running the script from a directory without node_modules.
- Fix: Navigate to the script's directory and install dependencies:
Double-check there's acd /var/www/html/nodejs/ npm installpackage.jsonfile in the directory listing your required packages.
内容的提问来源于stack exchange,提问作者Philipp M

