I created a task in Visual Studio Code to fetch some data from a web API and put it in the project files. For the fetch task, I tried to use the "axios" node module, which I installed globally:
npm install -g axios
npm list -g axios
axios@1.7.9
However, when I try to run the task, it fails with an error that 'axios' can't be found.
Error: Cannot find module 'axios'
This is the javascript file:
const axios = require('axios');
async function downloadFile() {
var url = "some-url"
const response = await axios.get(url);
console.log(response.data);
}
async function main() {
await downloadFile();
}
main();
And this is the tasks definition JSON file:
{
"version": "2.0.0",
"tasks": [
{
"label": "Fetch Project Data Files",
"type": "shell",
"command": "node",
"args": [
"${workspaceFolder}/.vscode/fetch-data-files.js"
],
"group": {
"kind": "build",
"isDefault": true
},
}
]
}
What am I doing wrong here? Why won't the task runner recognize global node modules? I know that I can use http instead of axios, install axios locally, or some other workarounds, but I'm trying to understand the underlying problem.
I found the solution. Press CTRL+SHIFT+P to open the commands window, select Preferences: Open User Settings (JSON)
to open the JSON configuration file for VS code.
Then add the following lines (replace USERNAME with your own windows profile username):
"terminal.integrated.env.windows": {
"NODE_PATH": "C:\\Users\\USERNAME\\AppData\\Roaming\\npm\\node_modules"
}
This will set the NODE_PATH variable for the integrated terminal in VS Code which is used to run the tasks, and with the NODE_PATH set, it will know where to find the global installed packages.
Note: In most cases, this would not be the best practice. It would be better to install dependent modules inside the project that depends on them, to avoid version conflicts and to make sure it will work in different environments without problems.