抱歉,您的浏览器无法访问本站

本页面需要浏览器支持(启用)JavaScript


了解详情 >

为了少敲几次命令,研究了一晚上脚本

首先上成果:

new-post

点击运行按钮,输入文章标题,回车


添加方法

打开hexo博客的目录,找到package.json,在"build": "hexo generate",的上面(大约在第6行)插入以下内容:

1
2
"new-draft": "hexo-new draft",
"new-post": "hexo-new post",

接下来复制以下脚本文件到博客目录/node_modules/.bin/下:

创建SH文件hexo-new,用于Linux:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")

case `uname` in
*CYGWIN*|*MINGW*|*MSYS*) basedir=`cygpath -w "$basedir"`;;
esac

read -p "Please enter a title:" title

if [ -x "$basedir/node" ]; then
"$basedir/node" "$basedir/../hexo/bin/hexo" new "$@" "$title"
ret=$?
else
node "$basedir/../hexo/bin/hexo" new "$@" "$title"
ret=$?
fi
exit $ret

创建hexo-new.cmd文件,用于Windows:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
@ECHO off
SETLOCAL
CALL :find_dp0

IF EXIST "%dp0%\node.exe" (
SET "_prog=%dp0%\node.exe"
) ELSE (
SET "_prog=node"
SET PATHEXT=%PATHEXT:;.JS;=;%
)

set /p title=Please enter a title:

"%_prog%" "%dp0%\..\hexo\bin\hexo" new %* "%title%"
ENDLOCAL
EXIT /b %errorlevel%
:find_dp0
SET dp0=%~dp0
EXIT /b

创建hexo-new.ps1文件,用于WindowsPowerShell:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#!/usr/bin/env pwsh
$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent

$title = Read-Host

$exe=""
if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {
# Fix case when both the Windows and Linux builds of Node
# are installed in the same directory
$exe=".exe"
}
$ret=0
if (Test-Path "$basedir/node$exe") {
& "$basedir/node$exe" "$basedir/../hexo/bin/hexo" new $args "$title"
$ret=$LASTEXITCODE
} else {
& "node$exe" "$basedir/../hexo/bin/hexo" new $args "$title"
$ret=$LASTEXITCODE
}
exit $ret

到这里就可以正常使用了,我是在Windows上测试的,cmd脚本可以正常使用,如果其它脚本有问题请留言

以下是我的笔记时间


笔记

  • 原理是通过npm脚本调用当前系统的脚本来执行命令的。

  • npm会将当前目录下的node_modules/.bin/目录添加到临时环境变量,所以可以在script中直接写脚本名称

  • hexo-new 脚本复制于同目录的hexo脚本,在其上改一下命令,添加引导用户输入的命令就可以实现了。

  • npm脚本相关知识参考自;

评论