Need Help Understanding Node JS Syntax Error - node.js

Can anyone please help me to understand the syntax error based on the attached screenshot below?
My script is supposed to access a given JSON and return the specific value, but somehow it's returning this error.
Edit 1
I tested my script with a dummy JSON and the script didn't return any error, so I suspect my original JSON might be giving problem. Here's my JSON.
{
"og_object": {
"id": "1192199560899293",
"description": "Hi everyone I have an important announcement to make. So ever since Penny started school, I've been having mixed feelings. \u00a0Besides having a bit of space to myself to breathe and rest my brain/legs, I'm actually a bit bittersweet cos my little baby, who used to sleep at weird hours and gobble puree",
"title": "Fighter and Penny's new sibling",
"type": "article",
"updated_time": "2017-04-12T01:17:57+0000"
},
"share": {
"comment_count": 0,
"share_count": 109
},
"id": "http://fourfeetnine.com/2017/03/05/fighter-and-pennys-new-sibling/"
}
Edit 2
Here's my script that I run that produces the error.
var objects = require('./output.txt');
console.log(objects);
output.txt is the file that contains the JSON that I pasted in Edit 1

var objects = require('./output.txt');
The require() function belongs to the module loading system. Despite the name, it can actually load several types of files and directories and not only Node modules. As per the high-level algorithm in pseudocode shown in docs:
require(X)
If X begins with './' or '/' or '../'
a. LOAD_AS_FILE(Y + X)
[...]
LOAD_AS_FILE(X)
If X is a file, load X as JavaScript text. STOP
If X.js is a file, load X.js as JavaScript text. STOP
If X.json is a file, parse X.json to a JavaScript Object. STOP
If X.node is a file, load X.node as binary addon. STOP
Since you get SyntaxError, output.txt does not contain valid JavaScript code.
If you really want to load JSON, you need to enforce subrule #3 by renaming the file to output.json.

Thanks to #Jordan suggestion. The fault is indeed due to wrong file extension. After changing the file extension from .txt to .json, then the syntax error disappeared.

Related

open() throwing mypy issues which reading an image file

I have the following line of code which reads an image (which is fed into a POST request):
files = {"image": (image_path, open(image_path, "rb"))}
While trying to run this through mypy, it keeps throwing the following error:
Argument 1 to "open" has incompatible type "Optional[str]"; expected "Union[Union[str, bytes, PathLike[str], PathLike[bytes]], int]"
I've tried searching this, but I've not found a solution for similar problems.
Is there a different way to read filepaths in order to avoid these issues?
Not the correct answer but if you want to temporarily make it go away to move ahead:
# type: ignore
at the end of the erroring line should work.

One .po file for each .py script

In my package, I would like to use one .po file for each .py script it contains.
Here is my file tree :
foo
mainscript.py
commands/
commandOne.py
locales/fr/LC_MESSAGES/
mainscript_fr.po
commandOne_fr.po
In the mainscript.py, I got the following line to apply gettext to the strings :
if "fr" in os.environ['LANG']:
traduction = gettext.translation('mainscript_fr', localedir='./locales', languages=['fr'])
traduction.install()
else:
gettext.install('')
Until now, it is working as expected. But now I would like to add another .po file to translates the strings in commandOne.py.
I tried the following code :
if "fr" in os.environ['LANG']:
traduction = gettext.translation('commandOne_fr', localedir='../locales', languages=['fr'])
traduction.install()
else:
gettext.install('')
But I get a "FileNotFoundError: [Errno 2] No translation file found for domain: 'commandOne_fr' "
How can I use multiple file like that ? The package being a cli, there is many strings in a single file because of the help man and verbose mode...etc and this is not acceptable to have a single .po file with hundreds of strings.
Note : The mainscript.py calls a function from commandOne.py, which is itself inherited from an abstract class that contains other strings to translate... so I hope if any solution exists that it will also be applicable to the abstract class file.
Thank you
Translations are retrieved from .mo files, not .po files, see https://docs.python.org/3/library/gettext.html#gettext.translation. Most probably you have to compile CommandOne_fr.po with the program msgfmt into CommandOne_fr.mo.
Two more hints:
What you are doing looks like a premature optimization. You won't have any performance problem until the number of translations gets really big. Rather wait for that to happen.
Why the _fr in the name of the translation files? The language code fr is already a path component.

How Do I resolve "Illuminate\Queue\InvalidPayloadException: Unable to JSON encode payload. Error code: 5"

Trying out the queue system for a better user upload experience with Laravel-Excel.
.env was been changed from 'sync' to 'database' and migrations run. All the necessary use statements are in place yet the error above persists.
The exact error happens here:
Illuminate\Queue\Queue.php:97
$payload = json_encode($this->createPayloadArray($job, $queue, $data));
if (JSON_ERROR_NONE !== json_last_error()) {
throw new InvalidPayloadException(
If I drop ShouldQueue, the file imports perfectly in-session (large file so long wait period for user.)
I've read many stackoverflow, github etc comments on this but I don't have the technical skills to deep-dive to fix my particular situation (most of them speak of UTF-8 but I don't if that's an issue here; I changed the excel save format to UTF-8 but it didn't fix it.)
Ps. Whilst running the migration, I got the error:
SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was too long; max key length is 767 bytes (SQL: alter table `jobs` add index `jobs_queue_index`(`queue`))
I bypassed by dropping the 'add index'; so my jobs table is not indexed on queue but I don't feel this is the cause.
One thing you can do when looking into json_encode() errors is use the json_last_error_msg() function, which will give you a bit more of a readable error message.
In your case you're getting a '5' back, which is the JSON_ERROR_UTF8 error code. The error message back for this is a slightly more informative one:
'Malformed UTF-8 characters, possibly incorrectly encoded'
So we know it's encountering non-UTF-8 characters, even though you're saving the file specifically with UTF-8 encoding. At first glance you might think you need to convert the encoding yourself in code (like this answer), but in this case, I don't think that'll help. For Laravel-Excel, this seems to be a limitation of trying to queue-read .xls files - from the Laravel-Excel docs:
You currently cannot queue xls imports. PhpSpreadsheet's Xls reader contains some non-utf8 characters, which makes it impossible to queue.
In this case you might be stuck with a slow, non-queueable option, or need to convert your spreadsheet into a queueable format e.g. .csv.
The key length error on running the migration is unrelated. It has been around for a while and is a side-effect of using an older version of MySQL/MariaDB. Check out this answer and the Laravel documentation around index lengths - you need to add this to your AppServiceProvider::boot() method:
Schema::defaultStringLength(191);

Attempting to append all content into file, last iteration is the only one filling text document

I'm trying to Create a file and append all the content being calculated into that file, but when I run the script the very last iteration is written inside the file and nothing else.
My code is on pastebin, it's too long, and I feel like you would have to see exactly how the iteration is happening.
Try to summarize it, Go through an array of model numbers, if the model number matches call the function that calculates that MAC_ADDRESS, when done calculating store all the content inside a the file.
I have tried two possible routes and both have failed, giving the same result. There is no error in the code (it runs) but it just doesn't store the content into the file properly there should be 97 different APs and it's storing only 1.
The difference between the first and second attempt,
1 attempt) I open/create file in the beginning of the script and close at the very end.
2 attempt) I open/create file and close per-iteration.
First Attempt:
https://pastebin.com/jCpLGMCK
#Beginning of code
File = open("All_Possibilities.txt", "a+")
#End of code
File.close()
Second Attempt:
https://pastebin.com/cVrXQaAT
#Per function
File = open("All_Possibilities.txt", "a+")
#per function
File.close()
If I'm not suppose to reference other websites, please let me know and I'll just paste the code in his post.
Rather than close(), please use with:
with open('All_Possibilities.txt', 'a') as file_out:
file_out.write('some text\n')
The documentation explains that you don't need + to append writes to a file.
You may want to add some debugging console print() statements, or use a debugger like pdb, to verify that the write() statement actually ran, and that the variable you were writing actually contained the text you thought it did.
You have several loops that could be a one-liner using readlines().
Please do this:
$ pip install flake8
$ flake8 *.py
That is, please run the flake8 lint utility against your source code,
and follow the advice that it offers you.
In particular, it would be much better to name your identifier file than to name it File.
The initial capital letter means something to humans reading your code -- it is
used when naming classes, rather than local variables. Good luck!

node js read files line by line

I am quite new with Node.js.
There is a folder on my computer where I have several textfiles (.fw4 format). I could find all the text files with the node-dir module.
Furthermore I need to get some content of each file from specified columns. Actually this algorithm works fine, using the readline module.
I keep my files name in an array.
Something like this: [ '000037592.fw4', '000037593.fw4', '000037594.fw4' ]
What do I need actually? I would like that this whole system would work synchronously and when I get the first file content (000037592.fw4) it would log something like end of file. And it continues reading the other files from the array.
So far, it has not worked how I wanted.
Thank you so much in advance. I would appreciate any suggestion on how to get a solution for my problem.
Do something like:
var fileArray = [ '000037592.fw4', '000037593.fw4', '000037594.fw4' ];
var i = 0;
readNextFile();
function readNextFile(){
fs.readFile(fileArray[i++], function(result){
handleResult(result);
if(i < fileArray.length){
readNextFile();
}
});
}

Resources