How can I use functions and libraries from Node.js to JavaScript? - javascript

I'm trying to use functions from Node.js to JavaScript but I don't know how to make the connection between them
I'm trying to use the next library in JavaScript
const mongoose = require('mongoose')
But the browser doesn't support "require"
Can any one helps me?

You can't directly use Node.js packages inside a Javascript file without a node environment. But there is a cool way of using Node.js packages inside your Javascript file.
Visit Skypack.dev and use any npm package using the CDN.
For example, mongoose - https://www.skypack.dev/view/mongoose
Write your javascript code like this,
<script type="module">
import mongoose from 'https://cdn.skypack.dev/mongoose';
</script>
Note: Make sure you add type="module" attribute to your <script> tag.
Thank you!

Related

Using GRPC-Web without NodeJS

How do you use GRPC-Web on the browser?
I mean, in pure browser code, without any NodeJS involved.
Official example from here: https://github.com/grpc/grpc-web/tree/master/net/grpc/gateway/examples/helloworld are mainly NodeJS oriented.
Is there way to use GRPC-Web in pure Javascript form without:
const {HelloRequest, HelloReply} = require('./helloworld_pb.js');
const {GreeterClient} = require('./helloworld_grpc_web_pb.js');
Meaning, just standard <script>-way of adding Javascript dependencies?
And be able to do: var client = new GreeterClient('http://localhost:8080');
Use grpc-web, not #grpc/grpc-js npm package.
The example provided in Write Client Code uses #grpc/grpc-js, which only works on NodeJS.
To use your protobufs and gRPC services defined in your .proto files, you need to generate your code using grpc-web. Then, import those generated files and use them.
Some things I learnt along the way:
You can't really use protobufjs with gprc-web in browsers, you need to use grpc-web and google-protobuf. If someone has an alternative solution, let me know please.
The generated code in grpc-web is not very nice - it is difficult to read and doesn't have all the features of protobufs. You need to have a lot of Javascript and bundling experience to use it.
grpc-web is more limited than gRPC. NodeJS runs gRPC, but in the browser, you have to use grpc-web, and must run a gRPC proxy to translate gRPC-web into/from gRPC.
Yes. You need to bundle your sources with webpack. This step is also described in the documentation you mentioned. At the bottom of the readme:
Just config your webpack to expose variable:
client.js
...
export function instantiateGreeterClient(...) {
return new GreeterClient(...)
};
webpack.config.js
module.exports = {
...
entry: './path/to/client.js',
output: {
path: './bundle/js/',
filename: 'grpc.js',
library: {
name: 'grpc',
type: 'umd',
},
...
}
And after that import your bundle as usual. Now you be able to use all defined variables in your script tag code as
<script src="path/to/grpc.js"></script>
<script>
const client = grpc.instantiateGreeterClient(...)
...
</script>
More information can be found in webpack documentation

How to access environment variables with vanilla javascript

I have an index.html and I need to pass some sensitive information to some JavaScript variables. This index.html contains plain javascript with jquery
so I am settning environmental variable like this:
USERNAME="123"
PASSWORD="password"
And I need to access this using javascript
<script>
var username = process.env.USERNAME;
var pw = process.env.PASSWORD;
</script>
but this gives the error
Uncaught ReferenceError: process is not defined
Maybe this is because I am using vanilla javascript. And I can't use any other framework other than jquery
Can someone help me how to do this?
I had this exact issue to deal with and I was able to create a working solution using this article. For this answer, I'll summarise the steps I took for a project deployed to Netlify and already modified to fit your question, but you can check out the article to see the base example and also learn more.
Note: This solution is ideal for small personal projects where the information is not exactly sensitive but you just don't want them
displayed so visibly in your code. Do not use for larger projects that require a reasonable level of security measures.
If your project is already deployed to Netlify, or a similar platform where you can add build/deploy commands:
Go to the build settings
If the script file you want to use the variables for is in a folder, set the build command to this: cd DIRECTORY-FOR-THE-SCRIPT-FILE && echo -e "export const USERNAME="123";\nexport const PASSWORD="password";" > config.js
If the script is in your root folder, set the command to this echo -e "export const USERNAME="123";\nexport const PASSWORD="password"; > config.js
In your index.html file where you import the script, set your script tag to include this attribute type="module" i.e <script src="./index.js" type="module"></script>
In your script file, import the variables by adding this line to the file: import {USERNAME, PASSWORD} from "./config.js"
Trigger a redeploy manually on Netlify, or it will be deployed automatically if you already set automatic deploys for the repo.
That's all!
This solved mine and I hope it helps anyone else✨.
So what is your environment? javascript runs in the frontend, where are you setting the env variable?
You may be able to use something like fs - https://www.npmjs.com/package/file-system to read from a file on the operating system, but I would not imagine most browsers would allow this

How to use Node.js packages within a client-side html document using browserify

I'm unable to use a node.js module on my website with broweserify. The example only shows how to run a javascript file that is separate from the .html file, not how to use the node.js module within the .html file. Seems like a trivial problem, but I'm unable to make it work.
Here's what I've done:
Initialized node.js & installed a package, npm i webtorrent-health as an example
Created require_stuff.js which consists of a single line: var WebtorrentHealth = require('webtorrent-health')
Run browserify: browserify require_stuff.js > bundle.js
Include package in my html document, e.g. <script src='bundle.js'></script>
Use the package somewhere in my document, e.g. like this: <script>webtorrentHealth(magnet).then(foobazbar())</script>
Despite bundle.js executing and seemingly defining webtorrentHealth, the script within the .html document fails with WebtorrentHealth is not defined. What am I doing wrong? How do I make it work? Thank you!
You're very close to what you want to achieve. In fact, your code bundle.js is inaccessible from outside (in your case the browser) due to browserify, but you can expose your module by writing at the end of your file require_stuff.js:
window.WebtorrentHealth = WebtorrentHealth;
Now you can use WebtorrentHealth in your document.

A very simple query - Loading plain old javascript file with webpack

Should be quite a common question for a webpack newbie but unfortunately couldn't find a solution -
My project uses webpack. I need to use a library but it needs to be used as the old way of adding script tag like
<script src="//messaging-public.realtime.co/js/2.1.0/ortc.js"></script>
However I am looking for some way through webpack (a loader or in some other way) such that I can use it like
import ortc from "realtime-framework"
or
import * as ortc from "realtime-framework"
You will need to either:
Install it from a package manager like npm;
Download the file locally and import it;
Or include it the normal way with a script tag, making sure it is included before your script.

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