使用GitHub仓库部署Node.js API时如何修改Azure构建目录
解决GitHub Actions部署Azure Web App时子目录Node.js项目构建失败问题
我要通过GitHub Actions部署位于仓库./anti-scraping-backend目录下的Node.js API到Azure Web App,但构建时始终在根目录执行,导致npm找不到子目录里的package.json,报错如下:
npm ERR! code ENOENT npm ERR! syscall open npm ERR! path /home/runner/work/Scraping-Anti-Scraping-Techniques/Scraping-Anti-Scraping-Techniques/package.json npm ERR! errno -2 npm ERR! enoent Could not read package.json: Error: ENOENT: no such file or directory, open '/home/runner/work/Scraping-Anti-Scraping-Techniques/Scraping-Anti-Scraping-Techniques/package.json' npm ERR! enoent This is related to npm not being able to find a file. npm ERR! enoent
尝试过单独执行cd ./anti-scraping-backend和修改deploy步骤的package参数,但问题依旧。
问题根源
GitHub Actions中每个run步骤都是独立的shell环境,单独的cd命令只会在当前步骤生效,后续步骤会自动回到仓库根目录,所以npm命令还是在根目录执行,找不到子目录的package.json。
解决方案
修改GitHub Actions配置文件,确保构建阶段的所有命令都在anti-scraping-backend目录下执行,同时调整打包和部署的路径匹配:
修改后的完整yaml配置:
name: Build and deploy Node.js app to Azure Web App - anti-scraping-api on: push: branches: - main workflow_dispatch: jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - name: Set up Node.js version uses: actions/setup-node@v3 with: node-version: '20.x' # 指定工作目录,让npm命令直接在子目录执行 - name: npm install, build, and test working-directory: ./anti-scraping-backend run: | npm install npm run build --if-present npm run test --if-present # 进入子目录打包,确保压缩包只包含API项目文件 - name: Zip artifact for deployment run: | cd ./anti-scraping-backend zip ../release.zip ./* -r - name: Upload artifact for deployment job uses: actions/upload-artifact@v3 with: name: node-app path: release.zip deploy: runs-on: ubuntu-latest needs: build environment: name: 'Production' url: ${{ steps.deploy-to-webapp.outputs.webapp-url }} permissions: id-token: write #This is required for requesting the JWT steps: - name: Download artifact from build job uses: actions/download-artifact@v3 with: name: node-app - name: Unzip artifact for deployment run: unzip release.zip - name: Login to Azure uses: azure/login@v1 with: client-id: ${{ secrets.AZURE_CLIENT_ID }} tenant-id: ${{ secrets.AZURE_TENANT_ID }} subscription-id: ${{ secrets.AZURE_SUBSCRIPTION_ID }} # 解压后文件在当前目录,直接部署当前目录内容 - name: 'Deploy to Azure Web App' id: deploy-to-webapp uses: azure/webapps-deploy@v2 with: app-name: 'anti-scraping-api' slot-name: 'Production' package: ./
关键修改说明
- 构建阶段指定工作目录:给npm步骤添加
working-directory: ./anti-scraping-backend,让npm命令直接在子目录执行,无需单独cd。 - 打包子目录内容:打包时先进入子目录,把内容打包到根目录的
release.zip,确保压缩包只包含API项目文件,没有多余的根目录内容。 - 部署阶段使用正确路径:解压后API文件在当前目录,所以
package参数设为./,Azure会直接部署当前目录的内容。
替代方案(同shell执行多个命令)
如果不想用working-directory,也可以把cd和npm命令放在同一个run块里(同一个shell环境):
- name: Change directory and run npm commands run: | cd ./anti-scraping-backend npm install npm run build --if-present npm run test --if-present
这样cd命令的效果会延续到后续的npm命令,同样能在子目录执行构建。
内容的提问来源于stack exchange,提问作者Arthur Konrad
相关产品推荐
相关产品推荐

