skip to Main Content

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?

2

Answers


  1. Chosen as BEST ANSWER

    Many thanks for the feedback and apologies for the format of the question....

    In answer to the second comment - from JRichardsz, Yes,I am trying to generate an output of random characters for password use using that code and would like to have it go directly into a .txt file from generation of the random characters.

    To JaredSmith - using the output.txt command does open a .txt document, but ideally I wanted to build something into the code to 'put' the generated output into a text file ready for saving.

    Sorry for any confusion, still getting to grips with terminology, etc.


  2. 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))
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search