Skip to content

Commit

Permalink
Improve Windows compatibility (#5)
Browse files Browse the repository at this point in the history
Co-authored-by: Sindre Sorhus <sindresorhus@gmail.com>
  • Loading branch information
TheBrenny and sindresorhus authored Mar 10, 2021
1 parent f98e599 commit 5258f2d
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 6 deletions.
13 changes: 8 additions & 5 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;/;
Expand All @@ -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;
}
Expand Down Expand Up @@ -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'));
Expand Down
4 changes: 3 additions & 1 deletion readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
13 changes: 13 additions & 0 deletions test_win.bat
Original file line number Diff line number Diff line change
@@ -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

0 comments on commit 5258f2d

Please sign in to comment.