找不到模块:Python、NodeJS 和 fs 模块

时间:2021-06-04 16:26:02

标签: python node.js json subprocess fs

使用 Python,我制作了一个要求输入(一个动作)的脚本。第二个选项在新的终端窗口中运行一个名为 settings.js 的 NodeJS 文件:

subprocess.call('start node src/settings.js', shell=True)`

在 NodeJS settings.js 文件中,它基本上使用 fs 来覆盖 config.json 中的键值。在这种情况下,将键 "PREFIX" 更改为用户输入的任何内容(例如 !)。

当它第一次读取 config.json 文件时,它显示一个错误。

代码:

await fs.readFile('config.json', 'utf8', async (err, data) => {
    // code to overwrite (with given data)
}

错误:

[Error: ENOENT: no such file or directory, open 'C:\Users\userhere\Desktop\serenity-zero\serenity-zero-test\config.json'] {
  errno: -4058,
  code: 'ENOENT',
  syscall: 'open',
  path: 'C:\\Users\\userhere\\Desktop\\serenity-zero\\serenity-zero-test\\config.json'
}

我认为这是因为它最初是从 python 脚本运行的,所以目录文件夹在 NodeJS 文件之外(python 脚本的文件夹目录)。我试过了:

await fs.readFile('src/config.json', 'utf8', async (err, data) => {
    // code
});

和,

await fs.readFile('./src/config.json', 'utf8', async (err, data) => {
    // code
});

但是,我得到了:

(node:17348) UnhandledPromiseRejectionWarning: Error: Cannot find module './src/config.json'
Require stack:
- C:\Users\userhere\Desktop\serenity-zero\serenity-zero-test\src\settings.js
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:880:15)
    at Function.Module._load (internal/modules/cjs/loader.js:725:27)
    at Module.require (internal/modules/cjs/loader.js:952:19)
    at require (internal/modules/cjs/helpers.js:88:18)
    at C:\Users\userhere\Desktop\serenity-zero\serenity-zero-test\src\settings.js:29:87
    at FSReqCallback.readFileAfterClose [as oncomplete] (internal/fs/read_file_context.js:63:3)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:17348) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:17348) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

请注意,当 python 脚本与 node.js 文件位于同一文件夹中时,此方法非常有效。我想让它更有条理,所以我将 node.js 文件放在 src 文件夹中。 python 脚本保留在原始文件夹中。在那之后,我收到了这个错误。

1 个答案:

答案 0 :(得分:0)

刚刚修复它,我所要做的就是将 config.jsonlaunch.py 文件放在同一目录中。我认为 config.json 不可能位于 src 文件夹中,但至少它可以工作。

相关问题