Windows 10下如何编写bat文件通过SCHTASKS运行指定Node.js文件
runnode.bat File for Your Scheduled Task Got it, let's work through this. Since batch files (.bat) run in Windows' command prompt environment (not Git Bash), we need to adjust your usual command to fit that context—plus, we want to make it reliable for a scheduled task, which might run with a different working directory or environment than your interactive Git Bash session.
The Most Reliable Batch File (Uses Absolute Paths)
This version avoids any dependency on the current working directory or system PATH settings, which is great for scheduled tasks that might run in a different context:
@echo off REM Switch to the directory where your Node.js script lives (critical if your script uses relative paths for assets/modules) cd /d "F:\Nodejs\project\subfolder" REM Run the script using the absolute path to node.exe (update this path if your Node.js install is in a different location) "F:\Nodejs\node.exe" "F:\Nodejs\project\subfolder\example.js"
Simplified Version (If Node is in Your System PATH)
If you've already added Node.js to your Windows system PATH (meaning you can run node from any command prompt without typing the full path), you can use this shorter version:
@echo off cd /d "F:\Nodejs\project\subfolder" node example.js
Quick Tips to Avoid Issues
- Why
cd /d? The/dflag ensures we switch both the drive (from C: to F:) and the directory in one command—without it,cdalone won't jump to a different drive letter. - Double-Check Paths: Scheduled tasks often default to working directories like
C:\Windows\System32, so using full absolute paths fornode.exeand your script prevents "file not found" errors. - Verify Permissions: Make sure the user account running the scheduled task has read access to the
F:\Nodejs\project\subfolderdirectory, and write access if your script creates or modifies files.
内容的提问来源于stack exchange,提问作者Piash

