Can output in Node automatically create a text file?

  Kiến thức lập trình

I am running a script using Node command prompt window, see following:

    // program to generate random strings

// declare all characters
const characters ='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';

function generateString(length) {
    let result = ' ';
    const charactersLength = characters.length;
    for ( let i = 0; i < length; i++ ) {
        result += characters.charAt(Math.floor(Math.random() * charactersLength));
    }

    return result;
}

console.log(generateString(500));

The output appears in the command prompt window, and needs to be copied and pasted to a text editor.

Is there any way to ‘automate’ Node (or something else) to extract the results and put in a text file for each execution command?

If so, ‘where’ do I put it (in the JS file?) or do I need something else?

4

Node has a built-in API called called writeFileSync, here’s an example of how to use it.

const fs = require('node:fs')

// ...

fs.writeFileSync('/path/to/output.txt', generateString(500))

Theme wordpress giá rẻ Theme wordpress giá rẻ Thiết kế website

LEAVE A COMMENT