I am trying to run node js file function from Laravel Controller function. Basically Node js file called as translate.js
have function which can translate input text to required language
( Like english to hindi etc..)
I have done some testing with debugging but each time I got an Error while execute Node script from Laravel Controller function.
Error I got :
The command ""node D:\Laragon\www\krutech\translate.js ""I want to try convert my text into hindi language."" hi"" failed. Exit Code: 1(General error) Working directory: D:\Laragon\www\krutech\public Output: ================ Error Output: ================ The filename, directory name, or volume label syntax is incorrect.
Where D:\Laragon\www\krutech\translate.js
is node js file inside root directory of Laravel Project.
Where D:\Laragon\www\krutech
is the Laravel Project
translate.js code:
const { translate } = require('@vitalets/google-translate-api');
function translateText(text, targetLang) {
return translate(text, { to: targetLang })
.then(res => {
return res.text;
})
.catch(err => {
console.error(err);
return "Translation failed";
});
}
module.exports = {
translateText: translateText
};
const textToTranslate = process.argv[2];
const targetLang = process.argv[3];
if (textToTranslate && targetLang) {
translateText(textToTranslate, targetLang)
.then(res => console.log(res))
.catch((err) => console.error(`Translation failed: ${err}`));
} else {
console.error('Please provide text to translate and target language code');
}
Laravel Controller Function code:
public function index()
{
$text = 'I want to try convert my text into hindi language.';
$targetLang = 'hi';
$pathToTranslateJS = base_path('translate.js');
$command = "node " . $pathToTranslateJS . " " . escapeshellarg($text) . " " . $targetLang;
$process = new Process([$command]);
$process->run();
if (!$process->isSuccessful()) {
throw new ProcessFailedException($process);
}
$translatedText = $process->getOutput();
return $translatedText;
}
When I try to run node file from command line with this command it is working fine and I am getting my required result.
CMD :
node translate.js "I want to try convert my text into hindi language." hi
Result :
मैं अपने टेक्स्ट को हिंदी भाषा में बदलने की कोशिश करना चाहता हूं।
But What is the problem with Laravel controller? I am not able to find how to solve?
My current Laravel version is 7.29