在bash脚本中使用进程替换时,Node无法找到模块

node can't find modules when using process substitution in bash script

本文关键字:Node 模块 替换 脚本 bash 进程      更新时间:2023-09-26

我有一个命令,我通常会在package.jsonscripts部分运行,但问题是npm run使用sh,它不支持进程替换。

我需要进程替换,因为我想把参数传递给flow-remove-types index.js的结果,而不能用管道来做。

所以我写了下面的脚本:
#!/bin/bash
PATH=./node_modules/.bin:$PATH
case $1 in
  start)
    node <(flow-remove-types index.js) ${@:2}
  ;;
  works)
    flow-remove-types index.js | node
  ;;
esac

现在的问题是,当我使用进程替代时,节点找不到安装的模块。在运行flow-remove-types index.js | node的case语句中使用works命令查找模块没有问题,但是当我使用进程替换运行start命令时。我得到以下堆栈跟踪

module.js:457
    throw err;
    ^
Error: Cannot find module 'moment'
    at Function.Module._resolveFilename (module.js:455:15)
    at Function.Module._load (module.js:403:25)
    at Module.require (module.js:483:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (/dev/fd/63:3:16)
    at Module._compile (module.js:556:32)
    at Object.Module._extensions..js (module.js:565:10)
    at Module.load (module.js:473:32)
    at tryModuleLoad (module.js:432:12)
    at Function.Module._load (module.js:424:3)

有人知道为什么会这样吗?为什么node不能访问node_modules中安装的模块

我猜当你运行:

flow-remove-types index.js | node

然后node尝试在当前工作目录中找到node_modules目录,因为它不知道脚本位于何处-它通过STDIN获得它。

但是当你运行:

node <(flow-remove-types index.js)

那么node不会在STDIN上获得脚本,而是在像/dev/fd/63这样的文件中,并且它将其文件名作为命令行参数。

试着看看结果是什么:

echo node <(flow-remove-types index.js)

它可能试图在/dev/fd中找到node_modules目录,但它不在那里。

也许这样做会有帮助:

NODE_PATH=`pwd`/node_modules node <(flow-remove-types index.js)

我不能测试它,因为对我来说:

node <(cat app.js)

不工作,即使app.js不需要任何模块