Javascript/Node/Twilio - ReferenceError: require is not defined - javascript

I have installed Node from:
Node
and run this in cmd:
npm install twilio
I then tried the example code provided by Twilio:
var accountSid = 'MyAccountSidHere';
var authToken = "MyAccountAuthTokenHere";
var client = require('twilio')(accountSid, authToken);
client.sms.messages.create({
body: "Jenny please?! I love you <3",
to: "SomeNumber",
from: "MyNumber"
}, function(err, message) {
process.stdout.write(message.sid);
});
Saved this to MyFile.js file and double clicked it.
I get the error message:
ReferenceError: require is not defined
This is my first encounter with JavaScript and I found a lot of similar questions, but have not been able to solve this.
I am to use this with QML, so I want to load it using:
import "MyFile.js" as MyFile
then call the javascript code as a function.

I've read a little into QML and I don't see how you could use a node.js module in QML. QML is used as a language where QT is the JavaScript engine and node.js is a server-side Javascript engine.
The require() function is a core function of node.js which is part of the engine. It's not something language-specific just like the window object in browser-based Javascript is not something in the Javascript language.
As I said in my comment, you should check out what node.js actually is: a server-side JavaScript engine, which executes JavaScript files. It is not a framework which you could load into another engine like QT.
Your code will run if you use it like this from the command-line:
node MyFile.js
I doubt this is helpful for your use-case as a QML import though.

Related

InternalError Metro has encountered an error: While trying to resolve module `child_process`

I am trying to call a function in a python file from a js file, I got this to work through my console, but I am now trying to implement it in a mobile app using expo.
The way I had set this up is, I have the JS file for a certain screen in my app, this then calls a function in a separate JS file, which then calls the function in the python file.
I am using the child_process module to talk to python from JS.
And as I said, this was working before I tried to export the JS function to my screen file.
index.js
export function foo(process, sentence){
const spawn = require("child_process").spawn;
const process = spawn("python3", ["./python.py", sentence]);
...
}
screen.js
*other imports
import { foo } from "./filepath..."
...
But when I run npm start I get the following error:
Failed building JavaScript bundle.
While trying to resolve module `child_process` from file `/Users/mee/Documents/GitHub/project/app/screens/screen.js`, the package `/Users/mee/Documents/GitHub/project/node_modules/child_process/package.json` was successfully found. However, this package itself specifies a `main` module field that could not be resolved (`/Users/me/Documents/GitHub/project/node_modules/child_process/app/screens/screen.js`. Indeed, none of these files exist:
How can I fix this?
It won't work for few reasons
child_process is part of the node standard library, it's not available in other environments like react-native or browser
even if above was not true, there is no python3 executable on your phone
python.py file from your local directory wouldn't be even uploaded to the phone because bundler is only uploading one big js file with entire js code combined + assets, python.py is neither of those.
Only solution that make sense it to rewrite that code to javascript.
Technically it's not impossible, there might be a way to do that, by compiling python interpreter for mobile platform, or using some tool that translates python code into js, but it's not something that you should consider.

How to use node Buffer module in a client side browser - detailed explanation required please

First things first. I know that there are other questions that are similar to this e.g. use NodeJs Buffer class from client side or
How can I use node.js buffer library in client side javascript
However, I don't understand how to make use of the reference to use browserify though it is given approval.
Here is my Node code:
import { Buffer } from 'buffer/';
I know this is the ES6 equivalent of require.
I would like a javaScript file implementation of this module so that I can simply use the standard html file reference:
<script src=./js/buffer.js></script>
And then use it as in for example
return new Buffer(temp).toString('utf-8');
This simply falls over with the
Uncaught ReferenceError: Buffer is not defined
no matter how I create the buffer.js file.
So using the browserify idea I've tried using the standalone script (from the https://www.npmjs.com/package/buffer as https://bundle.run/buffer#6.0.3 )
I've created a test.js file and put
var Buffer = require('buffer/').Buffer
in it and then run browserify on it as
browserify test.js -o buffer.js
and many other variations.
I'm not getting anywhere. I know I must be doing something silly that reflects my ignorance. Maybe you can help educate me please.
These instructions worked for me. Cheers!
Here are the instructions you can look at the web section.
https://github.com/feross/buffer
Here is what the instructions state about using it in the browser without browserify. So from what you tried
browserify test.js -o buffer.js
I would just use the version directly that does not require browserify
To use this module directly (without browserify), install it:
npm install buffer
To depend on this module explicitly (without browserify), require it like this:
var Buffer = require('buffer/').Buffer // note: the trailing slash is important!

How to use nodejs file with html file?

I have a frontend in HTML and JAVASCRIPT. I need to get value from nodejs file and display it in HTML label. So I create new node js file node.js as:
const Web3 = require('web3');
const web3 = new Web3('https://kovan.infura.io');
web3.eth.getBalance('0x9E632F36D8193a23ee76e7C14698aCF4b92869A2').then(console.log);
I include this file in script tag as:
<script src="node.js"></script>
First I want to look output in the console but it is giving an error
Uncaught ReferenceError: require is not defined
So, I try this code directly in HTML file within the script tag without including node file but still gives the same error.
Can somebody help me with this? I am new to use all this together.
Somehow, I managed to find a solution. I used browserify, which makes easy for me to run the nodejs code from my web app.
Browsers don't have the require method defined, but Node.js does. With Browserify you can write code that uses require in the same way that you would use it in Node.
browserify will recursively analyze all the require() calls in your app in order to build a bundle you can serve up to the browser in a single tag.
I referred this link: http://browserify.org/

ReferenceError: Can't find variable: require - JQuery error

I use this code in my .js file which is part of web site that is used via npm global http-server:
function getParsedStorage() {
let fs = require('fs');
return JSON.parse(fs.readFileSync('./../manager-data.json', 'utf8'));
}
and get errors:
jQuery.Deferred exception: Can't find variable: require (2) (exceptionHook — jquery.min.js:2:31584)
ReferenceError: Can't find variable: require (jquery.min.js:2:31697)
I've installed file-system package with npm install file-system --save but that didn't change anything.
It looks to me like you're attempting to make use of Node.js's require function from within a web browser without using a module system that provides a compatible require method.
Without additional information I can't be certain, however my advice would be to investigate a module loader like Require.js, SystemJS or Browserify which should all enable you to make use of this syntax in your module.
That being said, for the use case you're describing (accessing a JSON file from a website) you may be better served using a simple XHRHttpRequest or the fetch API.
The following is an example which makes use of the fetch API to return the parsed JSON file content.
// Returns a Promise that resolves to the parsed storage data
// NOTE: Lacks any error handling
function getParsedStorage() {
return fetch("../manager-data.json").then(response => response.json())
}

NodeJS - Add external module via code

Im having a nodeJS &express application which you can use like following:
var myNodeApp = require('myNodeApp');
my question is if there is a way to add to this application a new module/file by code
something like
var myNodeApp = require('myNodeApp');
myNodeApp.addModule("newModule")
or something like
myNodeApp.addFile("/path to the file")
That in run-time I will be able to read the content.
Im not talking about the typical import export(or npm install) module inside my node project(this is obvious) , I want that by code the developer(which use my node app) will be able to add file/module to my code which In RT I will be able to use.
Is it possible in node.js ?
I try to find referance about this topic without success...

Categories