Ramda.when结合fs.existsSync始终返回true的问题求助
解决Ramda.when与fs.existsSync配合使用的问题
问题根源
你用错了Ramda.when的核心规则:
- 第一个参数必须是谓词函数:得是返回布尔值的函数,不能直接传
fs.existsSync(path())这种已经执行完毕的布尔结果 - 第二个参数必须是待执行的函数:不能直接传
console.log(path())或fs.renameSync(...)的执行结果——这种写法会让操作在定义阶段就立刻执行,完全失去了条件判断的意义 - Ramda.when会返回一个新函数,必须调用这个返回的函数才会触发逻辑,你之前的写法没有完成这一步
修正示例
1. 修正bla2的写法
const bla2 = path => () => { // 把条件包装成函数 const checkExists = () => fs.existsSync(path()) // 把操作包装成函数 const logPath = () => console.log(path()) // 调用when返回的函数(这里传任意值即可,因为我们不需要用到这个参数) return R.when(checkExists, logPath)(undefined) }
2. 修正bla3的写法
原来的R.when(false, console.log('bla'))会直接执行console.log('bla'),因为第二个参数是函数的执行结果,正确写法:
const bla3 = () => { // 谓词函数返回false,处理逻辑包装成箭头函数 return R.when(() => false, () => console.log('bla'))(undefined) }
实际业务代码修正
针对你的文件移动逻辑,正确写法如下:
const moveEnvironmentVarsFile = (oldPath, newPath) => () => { // 检查文件是否存在的谓词函数 const fileExists = () => fs.existsSync(oldPath()) // 执行移动操作的函数 const moveFile = () => fs.renameSync(oldPath(), newPath()) // 触发when的条件判断与执行逻辑 return R.when(fileExists, moveFile)(undefined) }
额外优化(贴合Ramda函数式风格)
如果想减少箭头函数嵌套,可以用Ramda的curry简化:
const moveEnvironmentVarsFile = R.curry((oldPath, newPath) => { const fileExists = () => fs.existsSync(oldPath) const moveFile = () => fs.renameSync(oldPath, newPath) R.when(fileExists, moveFile)(undefined) }) // 使用时直接传入路径字符串即可 moveEnvironmentVarsFile('./old.env', './new.env')()
内容的提问来源于stack exchange,提问作者placplacboom
相关产品推荐
相关产品推荐

