Node.js REPL中.load命令无限循环及PowerShell替代命令报错求助
解决Node.js REPL加载文件无限循环及PowerShell兼容问题
问题背景
使用.load index.js在Node.js REPL中加载测试文件时,出现无限循环重复执行const mongoose = require('mongoose');的问题。在WSL2 Ubuntu环境中,node -i -e "$(< index.js)"可以正常加载文件并进入交互模式,但该命令在PowerShell中执行时会报错:
< : The term '<' is not recognized as the name of a cmdlet, function, script file, or operable program.
C:\Program Files\nodejs\node.exe: -e requires an argument
PowerShell兼容的替代方案
方案1:直接读取文件执行
在PowerShell中执行以下命令,即可加载index.js并进入交互REPL:
node -i -e "$(Get-Content index.js -Raw)"
-Raw参数确保Get-Content将整个文件内容作为单个字符串读取,避免换行导致的代码拆分问题,保证Node.js能正确执行完整的文件内容。
方案2:分步读取执行
如果遇到编码或特殊字符问题,可以拆分步骤执行:
# 读取文件内容到变量 $scriptContent = Get-Content index.js -Raw # 传递内容给Node.js执行并进入交互模式 node -i -e $scriptContent
原WSL命令失效原因
$(< index.js)是bash/zsh等类Unix Shell的语法,用于将文件内容作为命令替换结果返回。PowerShell不支持该语法,因此会将<识别为未知命令,导致报错。
测试用index.js代码
const mongoose = require('mongoose'); mongoose.set('strictQuery', false); mongoose.connect('mongodb://localhost:27017/movieApp', { useNewUrlParser: true, useUnifiedTopology: true }) .then(() => { console.log("CONNECTION OPEN!!!") }) .catch(err => { console.log("OH NO ERROR!!!!") console.log(err) }) const movieSchema = new mongoose.Schema({ title: String, year: Number, score: Number, rating: String }); const Movie = mongoose.model('Movie', movieSchema); const amadeus = new Movie({ title: 'Amadeus', year: 1986, score: 9.2, rating: 'R' });
内容的提问来源于stack exchange,提问作者pers0n
相关产品推荐
相关产品推荐

