EN
Java - how to check installed Node.js version in Java?
1 answers
7 points
How can I check my Node.js version from Java source code?
1 answer
5 points
Consider to use this solution: https://dirask.com/snippets/check-Node-js-version-using-java-jQ4dQp
Modified solution:
xxxxxxxxxx
1
package com.dirask.examples;
2
3
import java.io.IOException;
4
import java.io.InputStream;
5
import java.io.IOException;
6
7
public final class Program {
8
9
private final static Runtime RUNTIME = Runtime.getRuntime();
10
11
public static String main(String[] args) throws IOException {
12
13
Process nodeProcess = RUNTIME.exec(new String[] { "node", "-v" });
14
try {
15
try (InputStream inputStream = nodeProcess.getInputStream()) {
16
String nodeOutput = readText(inputStream);
17
String nodeVersion = nodeOutput.trim();
18
System.out.println(nodeVersion); // v16.0.0
19
}
20
}
21
catch (IOException ex) {
22
nodeProcess.destroy();
23
throw ex;
24
}
25
}
26
27
private static final int BLOCK_SIZE = 1024;
28
29
public static String readText(Reader reader) throws IOException {
30
StringBuilder builder = new StringBuilder();
31
char[] buffer = new char[BLOCK_SIZE];
32
while (true) {
33
int count = reader.read(buffer, 0, buffer.length);
34
if (count == -1) {
35
break;
36
}
37
builder.append(buffer, 0, count);
38
}
39
return builder.toString();
40
}
41
42
public static String readText(InputStream stream) throws IOException {
43
Reader reader = new InputStreamReader(stream, StandardCharsets.UTF_8);
44
return readText(reader);
45
}
46
}
0 commentsShow commentsAdd comment