Newer
Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
const path = require("path");
const fs = require("fs");
const qjsDir = path.resolve("./qjs");
const importRegex = /import .* from "\..*"/g;
const insert = (line, start, end, content) =>
[line.slice(0, start), content, line.slice(end)].join("");
// find all js files in qjs folder
const traverse = (dirname) => {
fs.readdirSync(dirname).forEach((file) => {
const fp = path.join(dirname, file);
if (path.extname(fp) === "") traverse(fp);
if (path.extname(fp) === ".js") {
// check if has file imports
const content = fs.readFileSync(fp).toString();
const found = content.matchAll(importRegex);
let wasChanged = false;
const lines =
found !== null
? content.split("\n").map((it) => {
const line = it.trim();
if (line.includes("import ") && line.includes('./') && !line.includes('.js')) {
const fixedLine = insert(
line,
line.lastIndexOf('"'),
line.lastIndexOf('"') + 1,
'.js"'
);
const split = fixedLine.split('"');
const importPath = split[split.length - 2];
const fullImportPath = path.resolve(
path.join(dirname, importPath)
);
const fileExists = fs.existsSync(fullImportPath);
const finalFixedLine = fileExists
? fixedLine
: insert(line, line.length - 2, line.length - 1, '/index.js"');
wasChanged = true;
return finalFixedLine;
}
return line;
})
: [];
if (wasChanged) {
console.log("Editing", fp);
fs.writeFileSync(fp, lines.join("\n"), { encoding: "utf8", flag: "w" });
}
}
});
};
console.log('\tStarting file traversal')
traverse(qjsDir);
console.log('\tCreating test file');
fs.writeFileSync('./qjs/testy.js', `
import connect from "./index.js";
const run = async () => {
try {
print('before connect')
const usp = await connect({
host: "iopsys.lan",
username: "admin",
password: "admin",
port: 9001,
protocol: "ws",
});
print('after connect')
const res = await usp.get("Device.DeviceInfo.");
print('get result')
print(JSON.stringify(res, null, 2))
await usp.disconnect();
print('after disconnect')
} catch(err) {
print("ERROR")
print(err)
print(err.stack)
}
};
run();
print('after run');
`)