Nightmare无法启动:代码存在语法错误(意外输入结束)
解决Nightmare跳转失败的语法错误问题
让我帮你排查这个问题——你遇到的SyntaxError: Unexpected end of input本质是代码里的嵌套结构(括号、大括号)没有正确闭合,再加上异步流程的写法有问题,导致Node.js没法解析完整的代码逻辑。咱们一步步来修复:
错误根源分析
你的代码里存在几个关键问题:
- 嵌套的
for...in循环、map箭头函数、request回调函数的大括号/括号没有一一对应闭合 - Nightmare的链式调用只写了
.goto(),没有完成后续的异步流程处理(比如.then()或.end()) console.log(ids[0])放在map内部,会在每次匹配到商品时重复打印,逻辑位置不合理
修复后的完整代码
var Nightmare = require('nightmare'); var nightmare = Nightmare({ show: true, height: 900 }); const request = require('request'); request('http://www.supremenewyork.com/mobile_stock.json', function(error, response, body) { // 处理request请求错误 if (error) { console.error('请求库存数据失败:', error); return; } const searchword = "Pinball"; const data = JSON.parse(body).products_and_categories; const ids = []; // 遍历所有商品分类 for (var key in data) { if (data.hasOwnProperty(key)) { // 遍历分类下的每个商品 data[key].forEach(item => { // 用forEach代替map,因为不需要返回新数组 if (item.name.indexOf(searchword) >= 0) { ids.push(item.id); } }); } } // 确保找到ID后再执行Nightmare跳转 if (ids.length > 0) { console.log('找到匹配的商品ID:', ids[0]); nightmare .goto(`http://www.supremenewyork.com/shop/${ids[0]}`) // 修正为商品详情页URL,更符合需求 .end() // 关闭Nightmare实例 .then(() => { console.log('跳转成功'); }) .catch(err => { console.error('跳转失败:', err); }); } else { console.log('没有找到匹配的商品'); nightmare.end(); // 记得关闭实例 } });
关键修改说明
- 闭合所有嵌套结构:把
request回调、for...in循环、forEach的大括号一一对应,彻底解决语法错误 - 优化商品遍历逻辑:用
forEach代替map(因为你只是收集ID,不需要生成新数组),逻辑更清晰 - 完善Nightmare异步流程:添加
.end()关闭浏览器实例,.then()和.catch()处理跳转成功/失败的情况 - 修正跳转URL:原代码跳转到Supreme首页,改成商品详情页的格式(
/shop/${id}),更贴合你查找商品后跳转的需求 - 增加错误处理:添加request请求失败的判断,以及无匹配商品的提示
现在运行修复后的代码,应该就能正常找到商品ID并完成跳转了。
内容的提问来源于stack exchange,提问作者pohzurrr
相关产品推荐
相关产品推荐

