I'm developing code in php, in app engine flexible environment. I'm trying to set up the SDK Admin, web version, for Firebase.
Currently, I'm just struggling with the following code:
$.ajax({
type: 'GET',
url: "prueba.js",
dataType: 'json'
}).done(function(res){
console.log("Todo bien!");
}).fail(function(jqXHR,textStatus,err){
console.log(err);
});
Aforementioned code is calling through AJAX the following code (that is, 'prueba.js'):
var admin = require(firebase-admin');
var serviceAccount = require('path/to/json-key.json');
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: 'https://<database>.firebaseio.com'
});
These code throws the exception:
SyntaxError: Unexpected token v in JSON at position 0
at JSON.parse (<anonymous>)
at n.parseJSON (jquery.min.js:4)
at ub (jquery.min.js:4)
at x (jquery.min.js:4)
at XMLHttpRequest.<anonymous> (jquery.min.js:4)
...and last but not least, the folder and files organisation:
'node_modules', containing firebase-admin, is located in the root folder ('web'), along with index.js, package.json and package-lock.json
Prueba.html and prueba.js are located in the path 'web/asg/trm/admin'
package.json in the 'web' folder holds the following code:
{
"name": "web",
"version": "1.0.0",
"description": "",
"main": "index.js",
"dependencies": {
"firebase-admin": "^6.0.0"
},
"devDependencies": {},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC"
}
'index.js', on the opposite hand, does not contain any code.
I have tested the following:
In 'require' (in 'prueba.js'), I've been juggling with different locations for the 'node_modules' folder (pointing directly to the 'package.json' comprised in 'firebase-admin' as well).
Due to my short experience in Node.js, I've been spending the last two days trying to make ends meet, with no success. So any kind help would be more than welcome!
Many thanks in advance!
url: "prueba.js",
dataType: 'json'
You're asking for a JavaScript file, but telling jQuery to parse it as JSON.
This is the first line of that JavaScript file:
var admin = require(firebase-admin');
… that the first character in it is the v that is being reported as an unexpected token. JSON cannot start with a v, but as mentioned what you have is not JSON.
It isn't client-side JavaScript either, it looks like it is intended to be part of a server-side program run on Node.js, which you said you were trying to use.
For some reason, you aren't running it using Node.js at all, but are delivering the source code to the web browser.
You could write your server-side program as a web service (the express library is popular for this) and then run it with Node.js. You should then set the url to be the URL of the end point you create with that.
Related
I am writing a node script that automates package updates within a package.json by reading the file, selecting the line with the package and giving the version a bump, and writing the new version of the file.
It runs fine when I run the script the first time. On the second run, readFileSync() gives a very different output, making the script break.
Here is the readFileSync function.
const data = fs.readFileSync("./package.json", {
encoding: "utf8",
});
On the first run, data logs like this:
PS C:\Projects\update-version-test> node updateversion.js
Updating package: webpack , version: patch
data {
"name": "update-version-test",
"version": "1.0.0",
"main": "index.js",
"author": "eendkonijn",
"license": "MIT",
"dependencies": {
"webpack": "^5.8.0"
}
}
The script works as expected, and the webpack package is bumped to 5.8.1. If I run the script again, however, the data logs like this:
PS C:\Projects\update-version-test> node updateversion.js
Updating package: webpack , version: patch
} } "webpack": "^5.8.1"",-test",
The package.json file is intact but somehow readFileSync() doesn't seem to pick it up correctly the second run?
When I make a manual change, the script seems to be working again. But only the one time.
I have a reproduction here:
https://github.com/eendkonijn/update-version-test
The problem is that you're trying to parse the json file using .split("\n") and later you assemble the resulting json content using .join(""). In the resulting file there will be no more line-breaks which is why your code does not work the second time.
Instead of manually parsing the json content, just parse it using JSON.parse, manipulate the webpack-property and finally overwrite the file content with the output of JSON.stringify. E.g:
const rawData = fs.readFileSync('./package.json', {
encoding: 'utf8',
});
const parsedData = JSON.parse(rawData);
parsedData.dependencies.webpack = 'callFunctionToManipulateTheVersionHere()';
fs.writeFileSync('./package.json', JSON.stringify(parsedData, null, 4));
I'm trying to build a desktop app for the first time, using the Electron framework, and I'm trying to use the Trilogy module. However, several errors keep popping out.
Basically, the main idea of my code is to have a button that enters a SQL database and checks whether the table "DATA" exists. (I know it's kind of lame, but I'm trying to test out the concept here so bear with me).
My main.js code is just the exact code found in the beginner tutorial, and seemed to be working fine before I imported Trilogy. The dependencies portion of my package.json was as follows:
"dependencies": {
"electron": "^2.0.16",
"sql.js": "^0.5.0",
"trilogy": "^1.4.5"
},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "electron ."
},
"devDependencies": {}
The head of my HTML code imported the script "tri.js", and then the body of my HTML code called that with:
<button onclick="search()">Produce Table</button>
<div id="table">table</div>
The file for "tri.js" contains the following code:
require('trilogy');
const db = new Trilogy('./storage.db');
function search()
{
var model = "THIS DOESN'T WORK";
document.getElementById('table').innerHTML = model;
if (db.hasModel('DATA')) {
model = "YES";
}
else {
model = "NO";
}
document.getElementById('table').innerHTML = model;
}
When this code is run using npm start, the outputted text in the div becomes "THIS DOESN'T WORK". I attempted to run it on my browser, but my browser wouldn't recognize "require" and "import" (I tried using both statements), with the error messages "Can't find variable require" and "Import calls expect exactly one argument", respectively. When the button is clicked, it then says "Cannot access uninitialized variable" at the line when I call the db.hasModel() function.
When I tried removing the import and require statement, and loading it straight into the HTML first, it outputs the error that "undefined is not a constructor".
Does anybody have any idea how to implement this so that I could do what I want to do? Or if not, any suggestions on how to further debug this would also be welcome. Thanks.
I have a Node.JS file that outputs page load analysis test results. I have stored the results in a file results.json, with JSON.stringify().
launchChromeAndRunLighthouse('https://www.microsoft.com/en-us/', flags, perfConfig).then(results => {
fs.appendFile('results.json', JSON.stringify(results), (err) => {
if(err){ throw err; }
console.log('Data was appended to file!');
var myObj = results.json; //problematic
var JSON_to_HTML = mustache.render('This test was generated at this time: {{generatedTime}}.', myObj); //problematic
});
});
Now I want to display the results in the browser, so I want to translate the JSON into HTML. I want to use mustache for this, but these lines aren't working for me:
var myObj = results.json;
var JSON_to_HTML = mustache.render('Test was generated at this time: {{generatedTime}}.', myObj);
I get the error "results isn't defined", the JSON file can't be read by mustache like this. I can't initialize "myObj" with the raw JSON, because it's about a million lines (and I need to later run tests for a whole bunch of pages, so I can't hardcode that right now).
I'm not sure how to translate this JSON file I have now into HTML. Does anyone have any ideas? I'm a beginner to Node and Mustache, any tips are highly appreciated.
A lot of googling led me to my own answer.
To read the JSON file of the test results and make an HTML page out of it, I had to create a package.json file for this Node module (ran npm init). After I created the file, I opened it in sublime and edited the scripts so a CLI command 'build' would take the .json file, take a .mustache file with the stuff I wanted to display from the .json file, and stick those in a .html file.
"scripts": {
"build": "mustache results.json basicTemplate.mustache > theDisplay.html",
"test": "echo \"Error: no test specified\" && exit 1"
},
results.json is where I stringified into, from the question. basicTemplate.mustache is for now
{{generatedtime}} {{initialurl}}
and theDisplay.html is just a basic html template (like this).
Now when I run node <name of node module>, the results file is generated. Then I run npm run build, and this script I just created in the package.json is run. That modifies theDisplay.html. You should now be able to double-click theDisplay.html in Finder, and a browser opens up with the time the tests were generated, as well as the url of the page tested.
I am working with electron-builder programmatically to generate installation packages. So far I have this as my utility to create the installation package for the current OS type:
const packagejson = require("../package.json");
const builder = require("electron-builder");
const Platform = builder.Platform;
function buildPromise(){
//Development package.json
const devMetadata = packagejson.electronBuilder;
//Application package.json
const appMetadata = {
name: packagejson.name,
version: packagejson.version,
description: packagejson.description,
author: packagejson.author,
productName: packagejson.productName
};
//Build for the current target and send back promise
return builder.build({
projectDir: "./",
devMetadata,
appMetadata
});
}
module.exports = {
buildPromise,
outputPath : packagejson.electronBuilder.directories.output
};
What it does is pull in the needed metadata from the apps MAIN package.json file which contains this section (so the application package.json is empty):
...
"electronBuilder": {
"build": {
"productName": "Node App",
"appId": "my.id",
"asar": false,
"win": {
"iconUrl": "http://localhost:5000/images/logo-multi.ico",
"target": "nsis"
},
"nsis" :{
"oneClick": false
}
},
"directories": {
"output": "electron/output",
"app":"electron/app",
"buildResources": "electron/buildResources"
}
}
...
When I run the build in Windows I get a file out called Node App Setup 1.0.0.exe. So far so go. But how do I actually control that final file name? Or at least retrieve that file name programmatically so I can read it in and respond to the client in some way? Obviously, I could piece it together from the json file settings but it I would rather it be more definitive.
You can specify the output filename using artifactName in the build section of your package.json.
The docs say the artifact file name template supports the ${ext} macro:
${ext} macro is supported in addition to file macros.
File Macros
You can use macros in the file patterns, artifact file name patterns and publish configuration url:
${arch} — expanded to ia32, x64. If no arch, macro will be removed from your pattern with leading space, - and _ (so, you don't need to worry and can reuse pattern).
${os} — expanded to mac, linux or win according to target platform.
${name} – package.json name.
${productName} — Sanitized product name.
${version} — from package.json
${channel} — detected prerelease component from version (e.g. beta).
${env.ENV_NAME} — any environment variable.
Any property of AppInfo (e.g. buildVersion, buildNumber).
Example
"build": {
"appId": "com.electron.app.my",
"artifactName": "node-app-${version}.${ext}",
...
},
If your package version is 1.0.0, a Windows target would output:
node-app-1.0.0.exe
At my request the author added it to the current version (8.5.1):
https://github.com/electron-userland/electron-builder/issues/899
so now we can do:
builder.build()
.then(paths => {
//paths contains an array of export file paths, e.g.:
console.log(paths[0]); //= c:/MyProject/dist/My Project Setup 1.0.0.exe
console.log(paths[1]); //= c:/MyProject/dist/myproject-1.0.0-x86_64.AppImage
});
I've been trying to create a Smart Package for the SkelJS framework.
The file is being loaded by the browser but when I try and access the object it exports it says its undefined. I'm using the following code in package.js:
Package.describe({
summary: "SkelJS for Meteor"
});
Package.on_use(function (api) {
api.use('jquery', 'client');
api.add_files(['skel.js'], 'client');
api.export('skel', 'client');
});
Also trying to access Package.skeljs.skel returns undefined as well.
In smart.json I'm using:
{
"name": "skeljs",
"description": "SkelJS for Meteor",
"homepage": "",
"author": "Giles Butler (http://giles.io)",
"version": "0.1.0",
"git": ""
}
I know SkelJS has been loaded because it logs to the console no configuration detected, waiting for manual init but then when I try and run skel.init() it returns undefined.
Any help or tips would be really appreciated.
Thanks
Giles
You also need to modify the first line of skel.min.js/skel.js
Within packages variable scoping still applies so you have to remove the var keyword if you want the file to let other files (such as package.js for api.export) access its variables.
The fix would be to change:
var skel=function() ....
to
skel=function() ....