Reading list Switch to dark mode

    Usage of node js in Magento 2

    Updated 19 September 2023

    Here’s a general overview of how you can use Node js with Magento 2.

    Installing Node js: – First, Make sure Node is already installed on your server.

    If not, visit this blog to install the node – Installing node using nvm

    Install Dependencies:– Depending on the specific task you want to achieve, you might need to install various Node js packages using npm (Node Package Manager).

    Use npm install package-name to install required dependencies at your Magento root.

    Searching for an experienced
    Magento 2 Company ?
    Find out More

    Example:

    npm install express
    npm install multer

    After installing the node packages via the npm a file named package.json will be created at the root and it looks like as below –

    {
      "dependencies": {
        "express": "^4.18.2",
        "multer": "^1.4.5-lts.1",
      }
    }

    Create Node js API:- Depending on the specific need create your node js API and place this file in the Magento root directory.

    So let us create a basic node API named server.js

    const express = require('express');
    const app = express();
    
    app.get('/api/data', (request, response) => {
      response.json({ message: 'Node js with Magento 2' });
    });
    
    const port = 8080;
    app.listen(port, () => {
      console.log(`Server is running on port ${port}`);
    });

    Note:- You can set the port dynamic by adding a field in the configuration (system.xml).

    Running Your Node js API:- At Magento 2 root run the below command to run the node server.

    node server.js

    Note:- You can also run the node server dynamically by creating a button (start and stop) in the Magento 2 configuration.

    • When hit the button to start the node server you can use the below code.

    <?php
    
    namespace Webkul\NodeWithMagento\Controller\Adminhtml;
    
    class Start extends \Magento\Backend\App\Action
    {
        /**
         * Api Url
         */
        public const API_URL = "server.js";
    
        /**
         * @var \Magento\Framework\Controller\Result\JsonFactory
         */
        protected $resultJsonFactory;
    
        /**
         * @var \Magento\Framework\App\Filesystem\DirectoryList
         */
        protected $directoryList;
    
        /**
         * @var \Magento\Framework\Shell
         */
        protected $shell;
    
        /**
         * @param \Magento\Backend\App\Action\Context $context
         * @param \Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory
         * @param \Magento\Framework\App\Filesystem\DirectoryList $directoryList
         * @param \Magento\Framework\Shell $shell
         */
        public function __construct(
            \Magento\Backend\App\Action\Context $context,
            \Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory,
            \Magento\Framework\App\Filesystem\DirectoryList $directoryList,
            \Magento\Framework\Shell $shell
        ) {
            parent::__construct($context);
            $this->resultJsonFactory = $resultJsonFactory;
            $this->directoryList = $directoryList;
            $this->shell = $shell;
        }
    
        /**
         * Execute method to start server
         *
         * @return \Magento\Framework\Controller\Result\Json
         */
        public function execute()
        {
            $response = new \Magento\Framework\DataObject();
            $response->setError(false);
            $data = $this->getRequest()->getParams();
            $response->setRoot($this->directoryList->getRoot());
            $rootPath = $this->directoryList->getRoot();
            $node = $this->shell->execute('whereis node');
            $nodePath = explode(' ', $node);
    
            if (!isset($nodePath[1]) || $nodePath[1] == '') {
                $node = $this->shell->execute('whereis nodejs');
                $nodePath = explode(' ', $node);
            }
            if (count($nodePath)) {
                $this->shell->execute($nodePath[1].' '.$rootPath.'/' . (self::API_URL) . " > /dev/null &");
                $response->setMessage(__('Server Started.'));
                $this->messageManager->addSuccess(__('Server has been started.'));
            } else {
                $response->setError(true);
                $response->addMessage(__('NodeJs Api Path not found.'));
                $this->messageManager->setError(__('NodeJs Api Path not found.'));
            }
    
            return $this->resultJsonFactory->create()->setJsonData($response->toJson());
        }
    }

    In the above code'whereis node' is a shell command that is used to locate the executable file for the Node js runtime in the system.

    • When hit the button to stop the node server you can use the below code.-

    <?php
    
    namespace Webkul\NodeWithMagento\Controller\Adminhtml;
    
    class Stop extends \Magento\Backend\App\Action
    {
        /**
         * @var \Magento\Framework\Controller\Result\JsonFactory
         */
        protected $resultJsonFactory;
    
        /**
         * @var \Magento\Framework\Shell
         */
        protected $shell;
    
        /**
         * @param \Magento\Backend\App\Action\Context $context
         * @param \Magento\Framework\View\Result\PageFactory $resultPageFactory
         * @param \Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory
         * @param \Magento\Framework\Shell $shell
         */
        public function __construct(
            \Magento\Backend\App\Action\Context $context,
            \Magento\Framework\View\Result\PageFactory $resultPageFactory,
            \Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory,
            \Magento\Framework\Shell $shell
        ) {
            parent::__construct($context);
            $this->resultJsonFactory = $resultJsonFactory;
            $this->shell = $shell;
        }
       
        /**
         * Execute method to stop server
         *
         * @return \Magento\Framework\Controller\Result\Json
         */
        public function execute()
        {
            $response = new \Magento\Framework\DataObject();
            $response->setError(false);
            $data = $this->getRequest()->getParams();
            $getUserPath = $this->shell->execute('whereis fuser');
           
            if ($getUserPath) {
                $getUserPath = explode(' ', $getUserPath);
                if (isset($getUserPath[1])) {
                    $stopServer = $this->shell->execute($getUserPath[1].' -k '.$data['port'].'/tcp');
                    $this->messageManager->addSuccess(__('Server has been stopped.'));
                }
            } else {
                $response->setError(true);
                $response->setMessage(__('Something went wrong.'));
                $this->messageManager->addError(__('Something went wrong.'));
            }
            return $this->resultJsonFactory->create()->setJsonData($response->toJson());
        }
    }

    In the above code fuser can identify the process using the files or sockets. And fuser can be also used to kill the process. So by using whereis fuser you can stop the server.

    Call Node js API in Magento 2:- Based on your need call node API in Magento 2 file such as in controllers, plugins, etc. via curl.

    As I have created a node API server.js above so I’m calling it in my controller.

    <?php
    
    namespace Webkul\NodeWithMagento\Controller\Index;
    
    use Magento\Framework\App\Action\Action;
    use Magento\Framework\App\Action\Context;
    
    class Index extends Action
    {
        /**
         * @var \Magento\Framework\Json\Helper\Data
         */
        protected $jsonHelper;
    
        /**
         * @var \Magento\Framework\Controller\Result\JsonFactory
         */
        protected $resultJsonFactory;
    
        /**
         * @var \Magento\Framework\HTTP\Client\Curl
         */
        protected $curl;
    
        public function __construct(
            Context $context,
            \Magento\Framework\Json\Helper\Data $jsonHelper,
            \Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory,
            \Magento\Framework\HTTP\Client\Curl $curl
        ) {
            parent::__construct($context);
            $this->jsonHelper = $jsonHelper;
            $this->resultJsonFactory = $resultJsonFactory;
            $this->curl = $curl;
        }
    
        public function execute()
        {
            $apiUrl = 'http://localhost:3000/api/data';
            $this->curl->get($apiUrl);
            $response = $this->curl->getBody();
            $data = $this->jsonHelper->jsonDecode($response, true);
            
            // Return the API response as JSON
            $result = $this->resultJsonFactory->create();
            return $result->setData($data);
        }
    }

    That’s all about of Basic usage of node js in Magento 2. Hope this will be helpful.

    Thanks for visiting the Webkul blog! 🙂

    Happy Coding!

    . . .

    Leave a Comment

    Your email address will not be published. Required fields are marked*


    Be the first to comment.

    Back to Top

    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home