Uncaught SyntaxError: Unexpected token '<' When I use libarchive.js - javascript

I'm trying to use libarchive.js to decompress a zip file that protected by a password.
import {Archive} from 'libarchive.js/main.js';
Archive.init({
workerUrl: 'libarchive.js/dist/worker-bundle.js'
});
document.getElementById('file').addEventListener('change', async (e) => {
const file = e.currentTarget.files[0];
const archive = await Archive.open(file);
let obj = await archive.extractFiles();
console.log(obj);
});
When I run this code, the console shows below output.
I have tried many workerUrl like below. But the result is same.
workerUrl: 'libarchive.js/dist/worker-bundle.js'
workerUrl: '/libarchive.js/dist/worker-bundle.js'
workerUrl: '../libarchive.js/dist/worker-bundle.js'
workerUrl: '../../libarchive.js/dist/worker-bundle.js'
workerUrl: '/node_modules/libarchive.js/dist/worker-bundle.js'
workerUrl: '../node_modules/libarchive.js/dist/worker-bundle.js'
workerUrl: '../../node_modules/libarchive.js/dist/worker-bundle.js'
What is the problem?
Thanks.

Whenever you see this:
▶ Uncaught SyntaxError: Unexpected token '<' some-file.js:1
It's usually because the request to load some-file.js returned an HTML page displaying a 404 error, but it's being interpreted as JavaScript and crashing on the very first character, which in the source of an HTML page is usually <.
To solve your problem, you can try the following URL from this answer:
/lib/worker-bundle.js
Or you can try to view worker-bundle.js directly in a browser. Either you will locate the correct URL, or you will learn that your server is simply not serving that file at all.

I used this code.
Archive.init({
workerUrl: '/libarchive.js/dist/worker-bundle.js',
});
And I put libarchive.js in /public folder of my Vue project.
It worked.

Related

Next js. error - unhandledRejection: Error: File './script.php' not found

there! I am developing app with Next js. and i need to run php script to get some value.
For executing php code I use '"exec-php' package from npm. this package requires enter php file path to js function. But when I put path as parameter to function and call this function, next js throws error - unhandledRejection: Error: File './script.php' not found.
execPhp('./script.php', (err, php, out) => {
php.test(obj, process.env.KEY, (err, result, output, printed) => {
signature = result;
});
});
If you have idea how to solve please answer. Thanks~

Accessing part of a URL via JavaScript, but not preceded by question mark

I'm building a React web app, where I want to use the query from a URL to search a MongoDB Database, and find an entry by its ID.
I have the following example URL:
www.examplewebsite.com/:id
In practice, the example URL would look like this in the browser:
www.examplewebsite.com/5f8da21ba227e300076c3299
Using JavaScript, how would I access the id (5f8da21ba227e300076c3299) from that URL?
I figured I may be able to do something like this...
const queryString = window.location.search;
console.log(queryString)
// 5f8da21ba227e300076c3299
However, since the ID is not preceded by a query question mark, I'm guessing that wouldn't work...
I could use a hacky approach of adding a '?' after the URL perhaps in my Router (this is for a React web app), however not sure that would be consistently the best approach.
Does anyone have any tips?
EDIT: I've added the suggestions below into my serverless function, and tried to log the result. Here's my code:
module.exports = async (req, res) => {
let urlOne = window.location.pathname.split('/').pop();
let urlTwo = window.location.pathname.split('/');
console.log(urlOne);
console.log(urlTwo);
};
It's returning the following error however when I call the function:
2020-10-23T10:23:37.878Z 91f31b36-0986-44a1-a7d1-fbd31e066ea6 ERROR Unhandled Promise Rejection {"errorType":"Runtime.UnhandledPromiseRejection","errorMessage":"ReferenceError: window is not defined","reason":{"errorType":"ReferenceError","errorMessage":"window is not defined","stack":["ReferenceError: window is not defined"," at module.exports (/var/task/api/fetchEditDebt.js:12:16)"," at Server.<anonymous> (/var/task/___now_helpers.js:813:19)"," at Server.emit (events.js:315:20)"," at parserOnIncoming (_http_server.js:790:12)"," at HTTPParser.parserOnHeadersComplete (_http_common.js:119:17)"]},"promise":{},"stack":["Runtime.UnhandledPromiseRejection: ReferenceError: window is not defined"," at process.<anonymous> (/var/runtime/index.js:35:15)"," at process.emit (events.js:327:22)"," at processPromiseRejections (internal/process/promises.js:209:33)"," at processTicksAndRejections (internal/process/task_queues.js:98:32)"]}
Unknown application error occurred
You can use:
window.location.pathname.split('/')

error: (-215) !empty() in function detectMultiScale in Opencv.JS

I have checked and tried these solutions here but none is helping
error: (-215) !empty() in function detectMultiScale
OpenCV.js - detectMultiScale "This Exception cannot be caught"
I also read elsewhere that the problem could be because the file needs to be served via an Http request and so I decided to use ngrok but I still found the same error. Currently am using python http.server
Here is the section of the code:
let classifier = new cv.CascadeClassifier();
let utils = new Utils('errorMessage'); //use utils class
let faceCascadeFile = "http://localhost:8000/docs/haarcascade_frontalface_default.xml";
//let faceCascadeFile = "D:\Code\Fit-to-Interact-web\docs\haarcascade_frontalface_default.xml"
//let faceCascadeFile = "https://0979da552cb5.ngrok.io/docs/haarcascade_frontalface_default.xml"; // path to xml
// use createFileFromUrl to "pre-build" the xml
//Make sure to run it in a webserver because it has to do XMLHTTPRequests.
utils.createFileFromUrl(faceCascadeFile, faceCascadeFile, () => {
classifier.load(faceCascadeFile); // in the callback, load the cascade from file
});
console.log(classifier.empty())
Worse when I use the absolute/relative file path I get this error Not allowed to load local resource or sometimes the same error:
Exception: OpenCV(4.4.0) /build/master-contrib_docs-lin64/opencv/modules/objdetect/src/cascadedetect.cpp:1689:
error: (-215:Assertion failed) !empty() in function 'detectMultiScale'

Error when calling file in same directory using node.js

Update: I was able to find the error in my code. The problem was that I didn't close my opening parenthesis with closing ones in my console.log for my notes.js.
I started a course on node.js and I am learning how to call other functions created from files on my local system. I have the directory node-notes in which I have two javascript files, app.js and notes.js. I am calling my notes.js in my app.js. I made a simple console.log() call just to make sure its working right in my notes.js. But when I try to run my code using the command node app.js I am getting the error below.
Update: I am using Node 10.0.0
I have no idea what this means so can someone please explain what the error is and how I can fix it. Below I will post both codes for my app.js and notes.js
app.js
console.log("STARTING app.js")
// calling modules using require
// calling functions in fs module and putting in the
// variable fs
const fs = require('fs');
const os = require('os');
const notes = require('./notes.js');
var user = os.userInfo();
console.log(user);
fs.appendFile('greetings.txt', 'Hello World!' + user.username , function(err){
if(err){
console.log("There was an error")
}else{
console.log("It was successful")
}
});
notes.js
console.log("Calling notes.js")
In notes.js you are missing a " to end the string.
console.log("Calling notes.js) should be console.log("Calling notes.js")
Thus you get a SyntaxError: Invalid or unexpected token

Node.js SyntaxError: Unexpected token in JSON at position 0

I have a JavaScript application which is running in Node.js environment and communicates to its clients ( also in JavaScript ) using a ZeroMQ. The messages come on the server in JSON format.
The application code throws it out
Node.js SyntaxError: Unexpected token in JSON at position 0
when it is parsed using JSON.parse(). I'm unable to figure out the issue. I've verified the JSON using http://jsonlint.com
Any help with JSON.parse() is welcome.
Edited:01/10/17, 15:33
Here are the client and server JavaScript code files. You'll need to create the .js files, can't post such a big code.
The JSON data file is also provided.
You'll need to launch the server.js and client.js and then the server console will print out the exception for unrecognized character.
https://www.4shared.com/folder/6VFJqrgU/javascript.html
Stackoverflow imposes link posting restrictions so had to post one link with all the files.
Just for info, I'm a C++ programmer, so don't bother about the code formatting or style of programming. I had to do it for a project need.
Edit 02/10/17, 11:50: Well it turns out that it is the JSON.parse() method which is unable to parse the json. But, I added a .trim() call to the args[1].toString() and the error has moved downstream. Unexpected token o in JSON at position 10. I don't understand what is wrong!!
Edit 04/10/17: Here is the minimal code.
var fs = require('fs');
try
{
var event = fs.readFileSync('demoReport.json', 'utf8');
console.log(event);
var eventObj = JSON.parse(event);
var reportName = event["ReportName"];
var reportData = event["ReportData"];
console.log(reportData);
}
catch(error)
{
console.log("JSON parsing failed: " + error);
}
This is the json:
{"EventName":"ReportGenEvent","TemplateFileNameLocation":"File location","ReportFormat":".pdf","ReportName":"TestReport","ReportLocation":"report location","Locale":"French","ReportData":{"dateTime":"2017-09-29T00:05:22.824Z","streamName":"","measurementTime":"2017-04-01T01:13:25.000Z","durationSeconds":0.0,"outOfBand":false,"notFinal":false,"newMeasurement":false,"savedFileName":"","measurementType":"Unknown","analysisElapsedSeconds":1.3462,"analysisElapsedCPUSecs":0.0624004,"geometryID":"GEOM","geometryDescription":"","measurementUUID":"6060c80f-007c-4992-88f8-55e2200d99b7","backgroundUUID":"","measurementWorkflowID":"Measurement","instrumentProperties":{"classCode":8,"description":"","manufacturer":"","model":"","properties":"locationName=Home latitude=25 longitude=20 elevation=30","serialNumber":"product/1","versionInformation":"=V1.0"}}}
Thanks.

Categories

Resources