Issue
This is the code used to open the file
The function used in code above
I have a crontab that run an script with the following command: usr/bin/node /services/integration/build/index.js
The cron log generates the following error: Error: ENOENT: no such file or directory, open './sql/search.sql'
My project folder structure: integration/ build/ sql/ src/
If I access my project folder and run node build/index.js, it works properly, what should I do o solve this issue?
I have already tried to move the sql folder
Solution
Probably the working directory of your process is not the project directory, but $HOME
. .
is relative to the working directory. You have to either use a path relative to the script file or change the working directory with cd
before running your script. See also this question on the Unix Stack Exchange.
From how you described your setup and paths in the question, I assume the project directory is /services/integration
, and the script has a relative path of build/index.js
and is trying to access /services/integration/sql/search.sql
. In this case:
To specify a path relative to the script file:
import { dirname, resolve } from 'path'
import { fileURLToPath } from 'url'
// Get equivalent of __dirname but within ESM
// This will contain `/services/integration/build`, assuming script file in "build" directory
const __dirname = dirname(fileURLToPath(import.meta.url))
// Get correct path for SQL file
const sqlFilename = resolve(__dirname, '../sql/search.sql')
-- OR --
To change the working directory with cd
:
Code in crontab (assuming correct project path is /services/integration
):
cd /services/integration && /usr/bin/node build/index.js
Answered By - CherryDT Answer Checked By - Senaida (WPSolving Volunteer)