Problems concerning require() javascript - javascript

I'm trying to run the JavaScript client for the Tumblr API but I'm getting a "require not defined" error. I've scoured almost every corner of SO trying to find a way to make it work.
I've managed to use Browserify to recognize it but at some point, I'm getting a fs.readFileSync error.
Then I tried RequireJS and again it does the require thing but I'm getting a Module name "something" has not been loaded yet for context"
I'm really new to Node.js but if I'm understanding it correctly the require() part isn't something the browser can do right? Can anyone guide me as to what solutions I can take for this? If it helps, I'm not planning to upload this on a server or anything. I'm just trying to run it on my local computer and just planning to run the API locally.
Edit:
Here's what I have on my main.js
var tumblr = require('index.js');
var client = tumblr.createClient({
consumer_key: '<consumer key>',
consumer_secret: '<consumer secret>',
token: '<token>',
token_secret: '<token secret>'
});
// Show user's blog names
client.userInfo(function (err, data) {
data.user.blogs.forEach(function (blog) {
alert('dang');
});
});
When I try requirejs, I do this to reference it <script data-main="script/main" src="scripts/require.js"></script>

It seems to me that you might be confusing server-side JavaScript (Node) and client-side JavaScript (in the browser). The Tumblr API you're trying to use is for Node only; you can't run it in a browser. You have to:
Install NodeJS and NPM on your system
npm install tumblr.js
Run the script with node <script name>
Start with the Tumblr.js example script, then customize for your own purposes!

Related

PYTHON module "requests" not working with packaged electron app

In my electron app I have a python file that has two import statements shown below
import requests
import shutil
The app works fine without an errors in the IDE but after packaging the electron app with
npx electron-packager ./ --platform=darwin --icon=src/img/logo.icns
The app gives me this error
It only gives this error for the 'requests' module but not the 'shutil' module. And yes, 'requests' is installed on my computer. I also use the PythonShell module in the js file to run the python file like below
function version_checker(){
form.classList.toggle('hide');
circle.classList.toggle('show');
let pyshell = new PythonShell(__dirname + '/version_checker.py');
pyshell.on('message', function (message){
console.log(message);
if(message !== "same"){
console.log("updating")
}
else{
if(message !== "restart"){
form.classList.toggle('hide');
circle.classList.toggle('show');
}
else{}
}
})
pyshell.end(function (err,code,signal) {
if (err) throw err;
console.log('The exit code was: ' + code);
console.log('The exit signal was: ' + signal);
console.log('finished');
});
}
I also do not wish to compile the python file into an executable because the python script "talks" to the js file. I am also on a M1 Pro Macbook running macOS Ventrua if that helps
How do I package the app and include the 'requests' module OR How do I make the 'requests' module work with the packaged app
I did find a stackoverflow post that asked a similar question but the owner voluntary took down the question so I wasn't able to view it
I looked at this post but it wasn't helpful because I'm not using 'anaconda' or 'child-process'
PythonShell just calls the system's Python interpreter, so use PIP to install the requests library
Or specify the interpreter as follows:
new PythonShell(__dirname + '/version_checker.py', {
pythonPath: '/path/to/python'
})
Note: For production purposes, it is recommended to include an interpreter in electron and install dependencies
It seems you just want to make a HTTP request, why not try fetch in javascript?
If the error is ModuleNotFoundError, then your python interpreter is struggling to find the requests module. This can happen for a number of reasons:
Module does not exist: We can rule this out if your ide ran program successfully.
2: Module is not where interpreter expects to find it: Most likely.
Almost certainly the python interpreter used by your IDE is different to the one you ran after packaging the electron app.
The solution is to either:
a. make sure the location of requests is visible to the PYTHONPATH by setting that in the proper location (I don't use MAC but I believe you have ~/.bash_profile file to set it in or
b. Explicitly add the request module location via a sys.path.append command in your code eg
import sys
import os
path = 'your path to request module'
sys.path.append(os.path.join(path, 'requests')
import requests
You should be able to find the path location by investigating your IDE and looking where you set the module to be included in your program

How put API key on env files in a Node.js app?

this is my first time im trying to handle " Web api ", so i took this project to get many call but after it running well, when i try to click to "search" it dosent work,
I guess the problem arises from api call because chrome inspector show me that :
I was able to understand on the different forums, for handling apis call with Node.js that must be encapsulated API calls behind "Environment variable".
That the config.js file
When i try to put on the terminal export env.API_KEY='000000000000000' it made me :
export: not valid in this context: env.API_KEY
I hope you can point me in the right direction, I very tried everything, to run it that.
I personally like to use a npm package called dotenv:
You can install it by running npm i dotenv within your api directory.
Have a file called .env within your api directory which contains all of your environment variables:
APP_ID="000000000000000"
API_KEY="000000000000000"
Then change config.js to load all environment variable files when it is executed by including require('dotenv').config():
require('dotenv').config()
module.exports = {
APP_ID: process.env.APP_ID,
API_KEY: process.env.API_KEY,
BASE_URL: 'https://api.adzuna.com/v1/api/jobs',
BASE_PARAMS: 'search/1?&results_per_page=20&content-type=application/json',
};
Note: you will also want to add .env to your .gitingore so that your sensitive API keys aren't included in your git repository

Problems using aws-sdk in the browser with browserify

I am working on browser based application that makes use of aws-sdk. I am using browserify for my app code but have not figured out how to roll aws into it. I have tried a couple of different approaches:
//MyApp.js - Take 1 using downloaded minified version
var AWS = require ('./aws-sdk.min.js');
...
AWS.config.region='us-east-2';
...
results in Cannot set property 'region' of undefined
My guess is that this doesn't work because browserify does not resolve the minified code.
//MyApp.js - Take 2 using downloaded development version
var AWS = require ('./aws-sdk.js');
This does not compile. Browserify reports Error: Cannot find module '../lib/core'.
Is there a trick to this that I am missing?
When I used AWS in the browser I set my region depending on the service I need, for example:
new AWS.EC2({apiVersion: '2016-11-15', credentials, region})
So this made me wonder, maybe the version you downloaded is encapsulated and not exposing anything for browserify.
First I tested the version in the browser as follows:
console.log(AWS)
<script src="https://cdnjs.cloudflare.com/ajax/libs/aws-sdk/2.184.0/aws-sdk.min.js"></script>
Everything looked good so then I went ahead and tested on browserify.
Turns out you are reassigning the AWS global variable when you do:
var AWS = require ('./aws-sdk.min.js');
But you are already bundling it, so you are good, what you need to do is the following:
require ('./aws-sdk.min.js');
// And then use it happily
AWS.config.region='us-east-2';
Without reassigning the AWS global variable

Script listed in Jade not accessible in my JavaScript

In running an express app, the Jade template includes two script lines:
script(src="https://cdn.socket.io/socket.io-1.3.5.js") <== library
script(src="main.js") <== my code
But when I call something defined in the first script from my JavaScript in main.js, I get the error:
Uncaught TypeError: Cannot read property 'connect' of undefined
The offending line is this one:
var io = io.connect();
Which is defined in the first socket.io script. How can I include that script in a way that my code in main,js can find it?
If this was server side, I'd just 'require' it.
Try this version
https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.3.5/socket.io.js
https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.3.5/socket.io.min.js
Socket io use browserify in order to compile the script into one file.
Probably the version you use is corrupt.
If this doesn't solve, try to use the npm socket-io.client lib.
npm install --save socket.io
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io();
</script>
Translate this into jade.
Regarding accessing the io javascript
You can check in your developer tools in network or console tab to find if the socket js is loading in your templates.
you can install it with node:
npm install socket.io
var io = require('socket.io')(80);
Other than that you can go directly to this page https://cdn.socket.io/socket.io-1.3.5.js and copy the code from that page into a local js file (socket.js or whatever you'd like to call it) and then require it as you would any other file.
Or find a different cdn to try and access it from.
Regarding the error you are getting
Have you defined io anywhere?

Basic requirejs concept needed to make work musicjson package

I'd like to use the musicjson.js package that helps to convert musicXML files into json notation, looking if it's a good way to import for example exported musicXML Finale scores into a browser playing with the Fermata/VexFlow class.
https://github.com/saebekassebil/musicjson
The thing is that this module works with require (calling for
nodes packages like fs) and I'm just a newbee in requirejs...Even if I spent few time in understanding the tutorial in the website, I don't still get how to solve this kind of basic problem when the dependencies of my musicjson.js need to be called like :
var xmldom = require('flat-xmldom'),
fs = require('fs'),
path = require('path'),
util = require('util');
My index.php page does the classic require call:
<!DOCTYPE html>
<head>
<!-- javascript head -->
<!-- REQUIRE -->
<script data-main="scripts/main" src="bower_components/requirejs/require.js"></script>
</head>
<body>
</body>
</html>
In my scripts/main.js, I'd like to do simply what it is told from musicjon :
var music = require('musicjson');
music.musicJSON(xml, function(err, json) {
// Do something with the MusicJSON data
});
I putted also, in the same directory scripts/, the flat-xmldom folder, fs.js, path.js, util.js
When I do this, I've just obtain this classic error of :
*Error: Module name "musicjson" has not been loaded yet for context: _. Use require([])*
...That looks like a common error referenced in the requirejs website,
but if I try things that I guess it should be written, I get a bit lost to determine where is the fundamental conceptual mistake here :
require.config({
baseUrl: '/scripts/',
paths: {
flatxmldom:'./flat-xmldom/__package__',
fs: 'fs',
path:'path',
util:'util',
musicjson: 'musicjson'
}
});
require(['flatxmldom','fs','path','util','musicjson'],function(flatxmldom,fs,path,util,musicjson){})
Error returned in this case for example :
*Module name "fs" has not been loaded yet for context: _. Use require([])*
Thanks a lot for your attention.
So, this is not a RequireJS problem per-se. The package you want to use is a Node.js package. It is intended to run in node (a server/desktop execution environment for JavaScript). It cannot/will not run in web page in a browser.
The packages it is trying to use (fs in particular) provide access to system resources such as the file system. Node provides these packages as part of its core libraries to any package that runs in node. A browser is specifically designed for security reasons never to allow direct access to such resources to any code that run in the browser because who knows where it came from or might try to do.
I haven't really tried to do this myself, but browserify (alternative to requirejs) claims that it will allow you to use any node package in your application.
If musicjson is at the heart of what your app should achieve and requirejs is a small step on the way to getting there, you could try your luck with browserify instead.

Categories

Resources