I want to have a strongloop example only using javascript without angular.
There's no complete working example without angular for now.
I want to simply include the browser.bundle.js in my index.html, then sync data from/to server side. In fact, I'm trying to replace pouchdb in my program since the couchdb seems not success in open source community.
I can't follow up this document correctly:
Running Loopback in the browser
create browser-app.js with the content from Running Loopback in the browser
copy past the content to browser-app.js
npm install loopback loopback-boot
browserify browser-app.js -o app.bundle.js Then I got error: Error: Cannot find module 'loopback-boot#instructions' from '/Users/simba/Projects/traveller-app/client/node_modules/loopback-boot'
There are few steps for this but its pretty simple.
Bootstrap your application via slc loopback.
Delete server/boot/root.js.
Uncomment two lines in server/server.js, it should look like:
...
// -- Mount static files here--
// All static middleware should be registered at the end, as all requests
// passing the static middleware are hitting the file system
// Example:
var path = require('path'); //this line is now uncommented
app.use(loopback.static(path.resolve(__dirname, '../client'))); //this line is now uncommented
...
Create index.html in the client dir (ie. client/index.html) with your contents.
That should get you a basic set up with just a basic front-end working. Let me know if you have any more issues.
Related
I have a react app that loads data from a local json file using
import data from './data.json'
it is all working fine without any issues and I'm able to open my index.html in 3000 and also open it as simple HTML page in browser.
Now I run npm run build which creates the build directory. However, my json values become kind of stagnant as it is hardcoded in the javascript in the build. So the question is how can my code in build directory reads json files from a specific location dynamically.
My question: Why not use fetch and serve the JSON from a server side API?
To partially answer your question:
Without changing any webpack configuration, you can use the import() function, instead of import, and a chunk will be built with the json content within a js file.
async function fn() {
const json = await import("./foo.json")
document.title = json.bar
}
On the other hand, probably, webpack has a way to configure this output to be json, but for that you'll need to npm run eject or use a tool to override the webpack production config.
Apart from other alternatives, what you're looking for vanilla Javascript is called fetch API. It's possible to read from either local or remote URLs via fetch method.
As per the example you provided above, instead of doing below;
import data from './data.json'
You can make use of it like;
fetch('./data.json')
Also it works pretty same way as per any URL;
// Sample working URL example to mock some real data
fetch('https://jsonmock.hackerrank.com/api/football_competitions?year=2015')
And best part of it, the parameter fetch method accept can be modified easily since it both accepts local file path and a URL as a variable very same way;
let baseURL = 'https://jsonmock.hackerrank.com/api',
endpointToCall = 'football_competitions',
year = '2015',
URL;
URL = `baseURL/${endpointToCall}?year=${year}`;
fetch(URL);
Note: With the last example above, my point is to destructure the same API endpoint used with previous example before, via dynamic variables in order to being able to more clearer. Please let me know if it's not and you need more clarification.
What you can do it before you run the npm run build you make a request to your server to get the data.json file and then just run the npm run build when it loads. You can write a simple script for it.
For example:
#!/bin/bash
# Get the file from the server
curl https://yourServer/data.zip -o data.zip
# Unzip the file, you can also use unzip
zip -d data.json
# Move the file to the desired directory
mv data.json /yourApp/data/data.json is
# Navigate to the directory where the npm package is
cd /yourApp/
# This one is optional but you should run a test to see if the app won't crash with the new json data that you fetched
# Run tests
npm run tests
# Run the build command for React
npm run build
You can modify this script with your paths and it should work.
Summary
Get the json data with curl
Unzip it
Move it to your react app where data.json is and replace it
Run the tests (optional)
Run the build
You're done.
Hope this helps.
I want to use MySQL database. I installed MySQL with command npm i mysql. In order to use it, I wrote:
var mysql = require('mysql');
But when I run the program, it shows ReferenceError: require is not defined error.
I wrote this line in home.ejs file within a script tag.
Home.ejs isn't the approriate file to write this line in.
ejs files won't contains that much logic (except condition and loop over some element in your dom).
Basically what you want to do is anodeJs script file which will connect to mysql, handle the request and serve your ejs files with your data.
Using express you'll have something like this in your node file :
app.get("/home",(req,res)=>{ res.render("home.ejs", {data : data}) (where data is what you get from your DB
By default require() is not a valid function in client side javascript. I recommend you look into require.js as this does extend the client side to provide you with that function.
you need to do your mysql processing before you get to the ejs template. Right now, you are trying to use require in a template, which is being rendered on the browser. You won't be able to do that without using a module loader like requirejs.
require() by default is a NodeJS function on the server side. You can use require.js like Abhilash said. It's bad practice to have mysql in the browser. Your username, password, and host will be exposed to the world.
The browser does not have an API that require modules. Also, this is something that you would do in a nodejs application (in the backend NOT the front end), typically in a .js file.
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...
I got an meteor app. On clientside I got a heavy calculation which freezes the whole tab in the browser while executing.
So I want to use Web Workers to avoid freezing and to handle the process better (terminating, loading informations percentages etc).
For getting the web workers to work I had to include a selfwritten webworker.js in my package.js.
So my main question is: How do I set up web workers in a meteor app (clientside)?
First I tried following things:
Add a file via api.addFile() with bare option.
Package.describe({
name: 'some:name',
version: '0.0.1',
// Brief, one-line summary of the package.
summary: 'Generates PDFs',
// URL to the Git repository containing the source code for this package.
git: '',
// By default, Meteor will default to using README.md for documentation.
// To avoid submitting documentation, set this field to null.
documentation: 'README.md'
});
Package.onUse(function(api) {
api.versionsFrom('1.1.0.2');
api.use(['mrt:redis#0.1.3'],
'server',
{weak: false, unordered: false}
);
api.addFiles([
"vendor/FileSaver.js",
"vendor/jspdf.debug.js",
"dcPDF.js"
],["client"]);
api.addFiles([
"server.js"
],["server"]);
api.addFiles(["pdfProgressWorker.js"],["client"], {bare: true});
api.export('DCPDF');
});
Meteor compresses all files in packages. To set up the workers right, I have to deploy the webworker.js as own js-file on clientside. The bare option seems not to work for this case. My js-files cannot call my webworker.js if I include the file in that way.
Second try:
I added my webworker.js to the /public folder.
Problem here: my webworker.js uses some external libaries which I already included in my own package. If I add the webworker.js to the public folder, I have to add all my external js-libaries too, which are all loaded on every site in my meteor app, which slows my whole application down. Not intended, not maintainable, not meteor-style (I think).
I am currently making a Meteor app and am having trouble reading files from the private subdirectory. I have been following a couple different tutorials and managed to get it to work flawlessly when I run the meteor app locally. This question (Find absolute base path of the project directory) helped me come up with using process.env.PWD to access the root directory, and from there I use .join() to access the private folder and the pertinent file inside. However, when I deployed this code, the website crashes on startup. I am very confident that it is an issue with process.env.PWD, so I am wondering what the proper method of getting Meteor's root directory on a deployed app is.
//code to run on server at startup
var path = Npm.require('path')
//I also tried using the below line (which was recommended in another Stackoverflow question) to no avail
//var meteor_root = Npm.require('fs').realpathSync( process.cwd() + '/../' );
var apnagent = Meteor.require("apnagent"),
agent = new apnagent.Agent();
agent.set('cert file', path.join(process.env.PWD, "private", "certificate-file.pem"))
agent.set('key file', path.join(process.env.PWD, "private", "devkey-file.pem"))
In development mode the file structure is different than after bundling, so you should never rely on it. Particularly, you should not access your files directly like you're doing with path methods.
Loading private assets is described in this section of Meteor's documentation. It mostly boils down to this method:
Assets.getBinary("certificate-file.pem");
and it's getText counterpart.
As for configuring APN agent, see this section of documentation. You don't have to configure the agent by passing file path as cert file param. Instead you may pass the raw data returned by Assets methods directly as cert. The same holds for key file ~ key pair and other settings.
As an alternative, you would need to submit your files independently to the production server to a different folder than your Meteor app and use their global path. This, however, would not be possible for cloud providers like Heroku, so it's better to use assets in the intended way.