9

How do I use Node Modules for example 'lwip' in React component ? This is for an electron application.

Updating the question with Code:

  1. This is the react component from which I am trying to invoke another .js file.

button.js

import React from 'react';
import ReactDOM from 'react-dom';
import resize from '../../node-code/process';

class Button extends React.Component{

    mess(){
        console.log('working');
        resize();
    }

    render(){
        return <button id="imgButton" onClick={this.mess.bind(this)}>Upload Image</button>
    }
}

export default Button
  1. This is the other javascript file where I am trying to resize the image.

process.js

var lwip = require('lwip');

export default function(){
    var lwip = require('lwip');
    lwip.open('../../public/img/portrait.jpg', function(err, image){


    image.batch()
        .scale(0.75)          // scale to 75%
        .rotate(45, 'white')  // rotate 45degs clockwise (white fill)
        .crop(200, 200)       // crop a 200X200 square from center
        .blur(5)              // Gaussian blur with SD=5
        .writeFile('../../public/img/output.jpg', function(err){

        });

    });
}
Vasista
  • 247
  • 1
  • 4
  • 14
  • Welcome to stack! This question needs some work. Are you encountering any errors? – azium Dec 15 '16 at 20:59
  • No errors yet but I need to know the process of invoking methods that are in the node modules. I am writing an electron application in which I need to process an image so I installed lwip node module how do I use the methods in react component ? Is there a tutorial which would guide me through ? – Vasista Dec 15 '16 at 21:05
  • like... `var lwip = require('lwip'); lwip.method()` ? – azium Dec 15 '16 at 21:42
  • Do I use this in the main.js (main process) of the electron or in the react component class ? – Vasista Dec 16 '16 at 15:35
  • you use it wherever you need it – azium Dec 16 '16 at 15:44
  • I have exported the function of resizing image using the lwip and when I try using that in a react component. It is throwing me this error. – Vasista Dec 16 '16 at 20:30
  • 'Uncaught TypeError: exists is not a function' – Vasista Dec 16 '16 at 20:30
  • update your question with the code you've written – azium Dec 16 '16 at 20:56

1 Answers1

8

The Node module needs to be executed from the main Electron thread, not the renderer thread on which React runs.

You can run NPM modules in the renderer process, as if you were in the browser, but those modules cannot use the Node.js library since obviously there is no Node in the browser.

To communicate between the main (Node) and renderer (browser) threads you need to use IPC (inter process communication) a system which uses events to send data between threads.

Here's the IPC documentation for Electron.

If you need constant communication between threads you can use the electron-ipc-socket library.

Pier
  • 10,298
  • 17
  • 67
  • 113