使用节点执行JS文件
Executing JS file using node
我有一个标记为 Index.js 的 node.js 脚本,我还有 1 个其他文件 bot.js。使用 Node.js 如何执行此文件?
var fs = require('fs');
const commandFiles = fs.readdirSync('./users/commands').filter(file => file.endsWith('.js'));
fs.watch('./users', (eventType, filename) => {
if (eventType === "rename" && filename.includes("txt") != true) {
let data = fs.readFileSync('./package.json', "utf8");
console.log("called");
fs.mkdirSync(`./users/${filename}/commands`);
commandFiles.forEach(element => {
fs.writeFileSync(`./users/${filename}/commands/${element}`, data);
});
fs.writeFileSync(`./users/${filename}/package.json`, data);
/*
EXECUTE bot.js HERE
*/
}
});
这是一种方法:
index.js 文件:
const { customCodes } = require('./bot.js');
console.log("Hello World from Node from index.js");
customCodes();
bot.js 文件:
customCodes = () => {
console.log('Code from Custom codes');
}
module.exports = {
customCodes
}
结果如下:
> nodemon server.js
[nodemon] 2.0.4
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,json
[nodemon] starting `node server.js index.js`
Hello World from Node from index.js
Code from Custom codes
还有更多方法,例如将某些内容设置为默认导出函数或 class。但这是最简单的方法之一。
我有一个标记为 Index.js 的 node.js 脚本,我还有 1 个其他文件 bot.js。使用 Node.js 如何执行此文件?
var fs = require('fs');
const commandFiles = fs.readdirSync('./users/commands').filter(file => file.endsWith('.js'));
fs.watch('./users', (eventType, filename) => {
if (eventType === "rename" && filename.includes("txt") != true) {
let data = fs.readFileSync('./package.json', "utf8");
console.log("called");
fs.mkdirSync(`./users/${filename}/commands`);
commandFiles.forEach(element => {
fs.writeFileSync(`./users/${filename}/commands/${element}`, data);
});
fs.writeFileSync(`./users/${filename}/package.json`, data);
/*
EXECUTE bot.js HERE
*/
}
});
这是一种方法:
index.js 文件:
const { customCodes } = require('./bot.js');
console.log("Hello World from Node from index.js");
customCodes();
bot.js 文件:
customCodes = () => {
console.log('Code from Custom codes');
}
module.exports = {
customCodes
}
结果如下:
> nodemon server.js
[nodemon] 2.0.4
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,json
[nodemon] starting `node server.js index.js`
Hello World from Node from index.js
Code from Custom codes
还有更多方法,例如将某些内容设置为默认导出函数或 class。但这是最简单的方法之一。