I am new to node and running a .js 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 node command prompt window, and needs to be copied and pasted to a text editor.
I am just wondering if there is any way to ‘automate’ node (or something else) to extract the results and put in a .txt file for each node execution command on the .js file?
If so, ‘where’ do I put it (in the .js file?) or do I need something else?
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))