0

I have a node.js script labeled Index.js, I have 1 other file bot.js. Using Node.js how can I execute this file?

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
        */
    }
});

1
  • Why not wrap that file in a module.exports and call it? Commented Jul 10, 2020 at 8:13

1 Answer 1

1

Here is one way to do it:

index.js file:

const { customCodes } = require('./bot.js');

console.log("Hello World from Node from index.js");

customCodes();

bot.js file:

customCodes = () => {
    console.log('Code from Custom codes');
}

module.exports = {
    customCodes
}

Result will be as follows:

> 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

There are a couple more ways such as setting something as a default exported function or class. But this is one of the simplest ways.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.