本文详解为何 window.alert() 在 node.js 中失效、require() 在浏览器中不可用,并分别提供浏览器端(基于 indexeddb)和 node.js 端的可行方案,帮助开发者根据运行环境选择正确的调试与用户交互方式。
本文详解为何 window.alert() 在 node.js 中失效、require() 在浏览器中不可用,并分别提供浏览器端(基于 indexeddb)和 node.js 端的可行方案,帮助开发者根据运行环境选择正确的调试与用户交互方式。
你遇到的问题根源在于混淆了前端(浏览器)与后端(Node.js)的执行环境。你的代码混合使用了仅在 Node.js 中可用的 require('sqlite3') 和仅在浏览器中存在的 window.alert(),导致无论在哪种环境中都无法正常运行。
示例(IndexedDB 查询并提示):
// 打开数据库const request = indexedDB.open('MyBookDB', 1);request.onupgradeneeded = (event) => { const db = event.target.result; if (!db.objectStoreNames.contains('beginner')) { db.createObjectStore('beginner', { keyPath: 'id' }); }};request.onsuccess = () => { const db = request.result; const tx = db.transaction('beginner', 'readonly'); const store = tx.objectStore('beginner'); // 查询 option 为 "verb to be" 的记录 const query = store.index('option').get('verb to be'); // 需提前创建 index query.onsuccess = () => { if (query.result) { // ✅ 浏览器中安全使用 alert(仅调试时) alert(`Found: ${query.result.option}`); // 生产推荐:document.getElementById('msg').textContent = `Found: ${query.result.option}`; } };};
⚠️ 注意:使用 IndexedDB 前需创建索引(store.createIndex('option', 'option')),且所有操作均为异步,不可直接 return 值。
修正后的 Node.js 示例:
const sqlite3 = require('sqlite3').verbose();const db = new sqlite3.Database('./mybook.db', sqlite3.OPEN_READONLY);const sql = 'SELECT option FROM beginner WHERE option = ?';db.all(sql, ['verb to be'], (err, rows) => { if (err) { console.error('Database error:', err.message); return; } if (rows.length === 0) { console.log('No matching record found.'); } else { rows.forEach(row => { console.log('✅ Found:', row.option); // ✅ 正确的日志输出 // 如需用户确认,可使用同步 prompt(需额外库)或启动 HTTP 服务返回响应 }); } db.close();});
通过环境隔离 + 技术栈对齐,即可彻底解决“代码无报错却无反应”的常见陷阱。