From 5258f2de39bcdd07f4bcbe4e430994b040b8f1e8 Mon Sep 17 00:00:00 2001 From: Jarod Brennfleck Date: Wed, 10 Mar 2021 20:48:45 +1100 Subject: [PATCH] Improve Windows compatibility (#5) Co-authored-by: Sindre Sorhus --- index.js | 13 ++++++++----- readme.md | 4 +++- test_win.bat | 13 +++++++++++++ 3 files changed, 24 insertions(+), 6 deletions(-) create mode 100644 test_win.bat diff --git a/index.js b/index.js index fece9aa..ab20740 100644 --- a/index.js +++ b/index.js @@ -2,6 +2,7 @@ const os = require('os'); const fs = require('fs'); const path = require('path'); +const childProcess = require('child_process'); function parse(string) { const reBashHistory = /^: \d+:0;/; @@ -19,10 +20,6 @@ function parse(string) { function getPath(options) { options = options || {}; - if (process.platform === 'win32') { - return ''; - } - if (process.env.HISTFILE) { return process.env.HISTFILE; } @@ -63,7 +60,13 @@ module.exports = options => { options = options || {}; if (process.platform === 'win32') { - return []; + const historyPath = getPath(options); + if (historyPath) { + return parse(fs.readFileSync(historyPath, 'utf8')); + } + + const {stdout} = childProcess.spawnSync('doskey', ['/history'], {encoding: 'utf8'}); + return stdout.trim().split('\r\n'); } return parse(fs.readFileSync(getPath(options), 'utf8')); diff --git a/readme.md b/readme.md index e228fcb..09b3c05 100644 --- a/readme.md +++ b/readme.md @@ -29,12 +29,14 @@ console.log(shellHistory.path()); Get an array of commands. -On Windows it will always be an empty array as command history is not persisted there. +On Windows, unless the `HISTFILE` environment variable is set, this will only return commands from the current session. ### shellHistory.path() Get the path of the file containing the shell history. +On Windows, this will return either the `HISTFILE` environment variable or `undefined`. + ### shellHistory.parse(string) Parse a shell history string into an array of commands. diff --git a/test_win.bat b/test_win.bat new file mode 100644 index 0000000..c3696a5 --- /dev/null +++ b/test_win.bat @@ -0,0 +1,13 @@ +:: Confirms that the batch file works correctly in Windows Terminal / Command Prompt. +:: This batch file is used to visually test to see if `shell-history` works, rather +:: than to act as a real, responsive "test case" (as such, `ava` is not used here). + +@echo off + +echo Print entire history +node --print "const history = require('.'); history()" +pause +echo. +echo Print last command (which will be "test_win.bat") +node --print "const history = require('.'); let h = history(); h[h.length - 1]" +pause