Try to use node.js, fs.read - javascript

This is how I am calling fs.read, but I'm continually getting an error. Is there something wrong here with my syntax?
The error on the command line is: "errorCode": -1,
var fs = IMPORTS.require('fs'),
sys = IMPORTS.require("sys")
var file= this.filename,
start= parseInt(offsetStart),
end= parseInt(offsetEnd);
bufSize = 64 * 1024;
fs.open(file,'r',0666,function(err,fd) {
fs.read(fd,bufSize,0,end,start,function(err,str,count) {
result = { reply:str,
reply2:count
};}); });

It might help if you explain what you are doing here. Why are you opening a file and what are you trying to read from it?
If it is a textfile it may be simpler to use a ReadStream something like this:
inp = fs.createReadStream('sample.txt');
inp.setEncoding('utf8');
inptext = '';
inp.on('data', function (data) {
inptext += data;
});
inp.on('end', function (close) {
console.log(inptext);
});
You might want to look at your code and ask yourself where the data in your return statement goes. If you really want to use a callback chain, you might try passing in an empty object, and then fill that with data, so that you don't have to worry about sending the data back up the callback chain.

if you expect up to 100k and the buffer is 64k, and the image is offset, could it be getting the first 57K of something starting around 7k?
What happens if the bufSize is 256 * 1024?
Can the values of offsetStart and offsetEnd be displayed or dumped? They seem worth knowing.
Also, is the second value really an offset, or is it a length?

Related

Object scoping rules seem to change due to seemingly irrelevant library?

So, I'm familiar with the general gist of JavaScript's features regarding objects. They're refcounted and if they go to zero, they die. Additionally, apple = banana where both are objects doesn't copy banana to apple but makes apple a reference to banana.
That being said, some of my code has something like this:
// imagine ws require() and setup here...
var RateLimit = require("ws-rate-limit")('10s', 80);
SickWebsocketServer.on("connection", function(mysocket, req){
// blahblahblah...
RateLimit(mysocket); // See below...
mysocket.on("limited", function(){console.log("someone was limited!"});
mysocket.on("message", function(data){
if(JSON.parse(msg).MyFlagToMessageASpecificWebsocketClient){ // obvs dont do this lol
findme = MyArr.find(guy=>guy.Socket==mysocket);
if(findme) console.log("TRIGGER PLS :)"); // GOAL
else console.log("DON'T TRIGGER"); // SOMETHING WENT WRONG
}
});
MyArr.push({MyName:"my SICK object", MyNumber:MyArr.length, Socket:mysocket})
}
The library used for rate limiting is called ws-rate-limit and I have pasted a shortened (non-code removed) version down below (since it's tiny). Imagine it to be in a package called ws-rate-limit (because it is :D).
const duration = require('css-duration')
module.exports = rateLimit
function rateLimit (rate, max) {
const clients = []
// Create an interval that resets message counts
setInterval(() => {
let i = clients.length
while (i--) clients[i].messageCount = 0
}, duration(rate))
// Apply limiting to client:
return function limit (client) {
client.messageCount = 0
client.on('newListener', function (name, listener) {
if (name !== 'message' || listener._rated) return
// Rate limiting wrapper over listener:
function ratedListener (data, flags) {
if (client.messageCount++ < max) listener(data, flags)
else client.emit('limited', data, flags)
}
ratedListener._rated = true
client.on('message', ratedListener)
// Unset user's listener:
process.nextTick(() => client.removeListener('message', listener))
})
// Push on clients array, and add handler to remove from array:
clients.push(client)
client.on('close', () => clients.splice(clients.indexOf(client), 1))
}
}
My issue is that, when I do use the RateLimit function, the "DON'T TRIGGER" code triggers. If I literally remove that one single line (RateLimit(mysocket)) it goes into "TRIGGER PLS :)".
The above is obviously logically simplified from my actual application but I think you get the gist. Apologies for any misspellings that may lead to undefineds or stuff like that; I promise you my code works if not for the RateLimit(mysocket) line.
When I add console.logs into the find function to log both the guy.Socket object and the mysocket object, with the RateLimit(mysocket) line, the mysocket object's .toString() returns [object global] rather than [object Object]. I know that this is some complicated JavaScript object scoping problem, but I have no clue where to start in terms of investigating it.
Thank you! :)
I'll take a random shot in the dark based on intuition. My best guess is that your issue is with the guy.Socket==mysocket line. Comparing objects that way will only check if they both point to the same heap memory location, even if it's two different stack variables. In your example I can only assume that the RateLimit(mysocket) line is somehow creating a new heap location for that stack variable (creating a new object from it) and because of that your == comparison is then no longer equal (even if they have the exact same values) because they're pointing to different locations.
Try using: JSON.stringify(guy.socket) === JSON.stringify(mysocket).

How to save strings to SPECIFIC location in p5.js

Here I have a code that I was playing around with.
It loads a string within my file and saves an unimportant one.
var file = "1";
var result;
var meString;
var splitMeString;
function preload() {
result = loadStrings("assets/save/"+file+".txt");
}
function setup() {
createCanvas(1000,650);
}
function draw() {
meString = result+'';
splitMeString = splitTokens(meString, ',');
text(meString,20,20);
console.log(splitMeString[2]);
}
function mousePressed(){
saveStrings("happy");
}
but how would I save a string to a specific location? Say I wanted to overwrite the file ("file")?
Questions like these are best answered by looking in the reference.
According to the reference, the saveStrings() function can take three arguments:
Syntax
saveStrings(list,filename,[extension])
Parameters
list String[]: string array to be written
filename String: filename for output
extension String: the filename's extension
So it sounds like you're looking for something like this:
saveStrings(yourArray, "file", "txt");
Also note that the third argument is optional, so this should also work:
saveStrings(yourArray, "file");
If you use the functions storeItem() and getItem() you can save strings to your program, this won't save it to a specific file embedded in your code but it will save it to your code. You can call whatever you stored in storeItem() with getItem()even after you close out of the tab. If you need any more info on it you can find it on the reference page here.
Hope this helps!

Getting a 'random' value from a module in node.js

Let's say I have a file that looks like this:
var random_nr = Math.floor(Math.random()*array.length);
var x = array[random_nr];
// do some things
exports.random_array_member = x
Now, if I 'require' this in another file, I will always get the same result as long as I don't restart my server, presumably because of caching?
What is the best way to run this code and get a random value, while not including the code into my main file?
The code you have shown is only executed once. The result from that code is then stored as a variable, ready to be exported to whatever file needs it.
Instead, you need to "call" the code at the moment you need a random variable:
exports.random_array_member = function(){
var random_nr = Math.floor(Math.random()*array.length);
return array[random_nr];
}
Now, instead of accessing exports.random_array_member, you call exports.random_array_member() in your other files.
Lets play with getters
random.js
var array = [1, 2, 3, 4, 5];
module.exports = {
get random_array_member() {
return array[Math.floor(Math.random()*array.length)]
}
}
consumer.js
var r = require('./random')
console.log(r.random_array_member)
console.log(r.random_array_member)
console.log(r.random_array_member)

Storage Error Laravel 5.1

So I've been having this annoying bug for quite some time and I've been hesitant to post here since it's not something you can fix unless you understand the entire code, but this is a really odd error that I'm not able to wrap my head around. I'll try to explain what I'm doing to the best of my ability. I just need to brainstorm and maybe think of possible reasons as to why this is happening. Any help would be really really appreciated! So, here goes.
I have a javascript call that's being made every 2 seconds. The javascript function makes an ajax call which sends a constantly changing value (a video's seek time for example) as so:
function startCron()
{
window.setInterval(function()
{
//Get all the variables, etc. etc.
$.ajax({
type: 'GET',
url: 'updateDetails',
data:
{
'seekTime': upSeekTime
},
success: function(updates)
{
alert(updates);
}
});
}
}, 2000);
}
Now this function works fine! It get's called every 2 seconds, it sends the correct values and it returns back and executes the success function.
Now, the function that my 'updateDetails' URL is calling a function which basically has a series of file operations. It involves opening one file, storing, opening a few other files, finally opening one last file, storing in it and returning back what it just stored. I know, that sounds pretty confusing and some might think it's inefficient, but hang in with me here.
//First file get and put process
$updatedSeekTime = round(Input::get('seekTime'));
$currentDetails = Storage::get("fileone");
list($fileID, $fileStatus, $fileSeekTime) = explode(",", $currentDetails, 3);
$storeMe = array(
"user_id" => $user_id,
"status" => $fileStatus,
"seek_time" => $updatedSeekTime
);
$storeMe = implode(",", $storeMe);
Storage::disk('local')->put($user_id, $storeMe);
//Now for the second file retrieving process
for($i=1;$i<=2;$i++) //Yes, 1 and 2 are file names.
{
$currentDetails = Storage::get($i);
list($fileID, $fileStatus, $fileSeekTime) = explode(",", $currentDetails, 3);
$allSeekKebabs[] = $fileSeekTime;
}
//Now I find all the minimum value from my array
$minSeekVal = min($allSeekKebabs);
//And the final file put process
$storeMe = array(
"user_id" => $user_id,
"status" => $fileStatus,
"seek_time" => $minSeekVal
);
$storeMe = implode(",", $storeMe);
//return $storeMe; //OKAY ATTENTION POINT 1
Storage::disk('local')->put($user_id, $storeMe); //PROBLEM POINT
//return $storeMe; //OKAY ATTENTION POINT 2
Now. If you've made it to this point, a cookie to you because I didn't think most people would read past my code. Ok, so now, here's the really really weird part. Attention point 1 gives me all the correct things. BUT, if I return the SAME variable right after that storage line, like in Attention point 2, the file just stores 0 as the last variable (seek_time according to the last storeMe array). Every other variable in that array comes out right. And the value of seek_time in storeMe is correct UNTIL that damn storage line. After that, the last variable becomes 0. So what it looks like to me is that the storage line is CHANGING my variable! Sounds crazy, right? I've been cracking my head on this for so long.
I have checked EVERY possible line before that problem point and everything is ayy-okay. But that damn line messes everything up and I just can't figure out why. My routes file is fine too!
Any help would be VERY appreciated. You can see how frustrated this thing's gotten me. All I'm asking for is, is there something I'm missing technically. I know that it's near impossible to get a direct answer in this situation, but just any thought, no matter how farfetched, do let me know!
Thanks a lot guys :D
Is $user_id a path that exists on your server ? because it should be:
https://laravel.com/api/5.1/Illuminate/Contracts/Filesystem/Filesystem.html#method_put
bool put( string $path, string|resource $contents, string $visibility = null)
Write the contents of a file.
Parameters
string $path
string|resource $contents
string $visibility
Return Value
bool

Error during synchronous write using Node.js

I have written code that parses a dictionary returned from Firebase containing images encoded using base64. I want it to simply write these images to file, and it does, but I receive the following error after my writes finish:
smalloc.cc:280: void node::smalloc::SliceOnto(const v8::FunctionCallbackInfo<v8::Value>&): Assertion `end <= source_len' failed.
This is my code:
// Iterate through each key in each page if each request
for (var key in request) {
var obj = request[key];
if (typeof (obj) == "object") {
for (var prop in obj) {
item++;
if(obj.hasOwnProperty(prop)) {
switch (prop) {
case "img":
var media = new ReceivedMedia(obj[prop]);
var filename = transaction.tid + "-" + item + "." + media.extension;
filename = filename.slice(10);
require('fs').writeFileSync(filename, media.b64, 'base64', function(err) {
if (err) throw err;
});
break;
}
}
}
}
}
My images come out fine, but the error is a little weird and I would prefer to not to occur. Would anyone have an idea as to why this is happening? That would be super helpful :)
Note: ReceivedMedia is a class I defined as:
function ReceivedMedia(media) {
this.b64 = media.b64;
this.extension = media.extension;
this.posx = media.posx;
this.posy = media.posy;
}
Side question: If I use writeFile instead of writeFileSync one of my images is corrupted and the other contains no data. If after that happens I run my node script again, the files save correctly. I would also like some explanation as to why that happens, from my understanding one of these is synchronous (writeFileSync I am guessing) and the other is asynchronous (writeFile I am assuming).
A Google search for your error message description found this discussion of the issue in io.js and this discussion in node.js and it sounds like it is a bug that has been fixed (not sure if the fix has been released in a full build yet).
The node.js fix is here.
If you were desparate to fix it now in your own build, you'd have to apply the fix to your own code tree and rebuild it. Otherwise, you'll have to investigate or inquire when this fix will get into an official release (I'm not personally sure how that process works for node.js).

Categories