简体   繁体   English

在另一个NodeJS进程中执行一个JS文件(带有日志等)。

[英]Execute a JS file (with logs, etc…) inside another NodeJS process

Here is my problem, I want to create a CLI that automatically runs a test. 这是我的问题,我想创建一个自动运行测试的CLI。 Without the CLI, I'm able to run everything perfectly with the node command: 没有CLI,我可以使用node命令完美地运行所有命令:

node test.js

Basically, I want to do the exact same thing as the command before, so I googled for a technique that does this. 基本上,我想做与之前命令完全相同的事情,所以我用谷歌搜索了一种执行此操作的技术。 I found this: 我找到了这个:

#!/usr/bin/env node
'use strict';
 const options = process.argv;
 const { execFile } = require('child_process');
 const child = execFile('node', ['../dist/test.js'], (error, stdout, stderr) => {
     if (error) {
        throw error;
     }
     console.log(stdout);
 });

This method doesn't work for me because, in the test.js file, I'm using the ora package. 此方法对我不起作用,因为在test.js文件中,我使用的是ora包。 And because this package is making real-time animations, it doesn't come in stdout . 而且由于此程序包正在制作实时动画,因此它不在stdout

Is there any way of executing in real time (without subprocess) my test.js using Node? 有什么方法test.js使用Node实时(无子过程)执行test.js吗? I'm open to other methods, but I want to publish the CLI on NPM, so keep in mind that it has to be in JavaScript 😊. 我对其他方法持开放态度,但是我想在NPM上发布CLI,因此请记住,它必须在JavaScript😊中。

You can find every file that I've talked here on GitHub . 您可以在GitHub上找到我所说的每个文件。 Normally, you wouldn't need this link, but I'm giving it to you if you need to have a closer look. 通常,您不需要此链接,但是如果您需要仔细查看,我会给您。

You should simply call your test() function from your CLI code, after requiring the module that defines it. 在需要定义它的模块之后,您应该仅从CLI代码中简单地调用test()函数。 Have a look at mocha and jasmine: you will see that while both tools provide a CLI, they also provide instructions for invoking the test frameworks from arbitrary JS code. 看一下mocha和jasmine:您将看到,虽然这两个工具都提供CLI,但它们还提供了从任意JS代码调用测试框架的说明。

I can't think of a way without a sub-process. 我想不出没有子流程的方法。 but this may help. 但这可能会有所帮助。 The child process exec will not work with the continuous output commands as it buffers the output the process will halt when that buffer is full. 子进程执行程序将不使用连续的输出命令,因为它将缓冲输出,当该缓冲区已满时,该进程将停止。

The suitable solution is spwan : 合适的解决方案是spwan

var spwan = require('child_process').spwan
var child = spwan('node', ['../dist/test.js'])

child.stdout.on('data', function(data) {
  console.log(data)
})

child.stderr.on('data', function(data) {
  console.log(data)
})

Here is my solution, you can use the fs library to get the code of the file, and then, you simply use eval to execute in the same process. 这是我的解决方案,可以使用fs库获取文件的代码,然后只需使用eval在同一进程中执行即可。

const fs = require("fs");

function run(file) {
    fs.readFile(file, (err, data) => {
        eval(data.toString('utf8'))
    })
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM