I'm NOT using the node load option
External js files ARE being called and loaded
The xlsx file to be imported IS local to the published files
This is the script so far - all I want to do is check to see if the source is being imported and populating the created workbook
var workbook = new ExcelJS.Workbook();
var importBook = "./story_content/external_files/sample.xlsx";
console.dir( importBook );
workbook.xlsx.readFile( importBook );
console.dir ( workbook );
var ws = workbook.getWorksheet("Sheet1");
console.dir( ws );
line 112 is the result of console.dir ( workbook ); which says to me that NOTHING is either loaded OR imported, and I can't understand why not....wasted too much time trying possible solutions so i'm reaching out to the community.
Thanks in advance for any insight
You can try this.
const filePath: string = `assets/1962.xlsx`;
const buffer = await fetch(filePath).then(res => res.arrayBuffer());
const workbook = new Workbook();
await workbook.xlsx.load(buffer);
const worksheet = workbook.getWorksheet(1);
console.dir(worksheet);
Related
How can I read a file in zig, and run over it line by line?
I did found os.File.openRead, but it seems old cause it says that container 'std.os' has no member called 'File'.
std.io.reader.readUntilDelimiterOrEof lets your read any std.io.reader line by line. You usually get the reader of something like a file by calling it’s reader() method. So for example:
var file = try std.fs.cwd().openFile("foo.txt", .{});
defer file.close();
var buf_reader = std.io.bufferedReader(file.reader());
var in_stream = buf_reader.reader();
var buf: [1024]u8 = undefined;
while (try in_stream.readUntilDelimiterOrEof(&buf, '\n')) |line| {
// do something with line...
}
The std.io.bufferedReader isn’t mandatory but recommended for better performance.
I muddled through this by looking at the Zig library source/docs, so this might not be the most idiomatic way:
const std = #import("std");
pub fn main() anyerror!void {
// Get an allocator
var gp = std.heap.GeneralPurposeAllocator(.{ .safety = true }){};
defer _ = gp.deinit();
const allocator = &gp.allocator;
// Get the path
var path_buffer: [std.fs.MAX_PATH_BYTES]u8 = undefined;
const path = try std.fs.realpath("./src/main.zig", &path_buffer);
// Open the file
const file = try std.fs.openFileAbsolute(path, .{ .read = true });
defer file.close();
// Read the contents
const buffer_size = 2000;
const file_buffer = try file.readToEndAlloc(allocator, buffer_size);
defer allocator.free(file_buffer);
// Split by "\n" and iterate through the resulting slices of "const []u8"
var iter = std.mem.split(file_buffer, "\n");
var count: usize = 0;
while (iter.next()) |line| : (count += 1) {
std.log.info("{d:>2}: {s}", .{ count, line });
}
}
The above is a little demo program that you should be able to drop into the default project created from zig init-exe, it'll just print out it's own contents, with a line number.
You can also do this without allocators, provided you supply the required buffers.
I'd also recommend checking out this great resource: https://ziglearn.org/chapter-2/#readers-and-writers
Note: I'm currently running a development version of Zig from master (reporting 0.9.0), but I think this has been working for the last few official releases.
To open a file and get a file descriptor back
std.os.open
https://ziglang.org/documentation/0.6.0/std/#std;os.open
To read from the file
std.os.read
https://ziglang.org/documentation/0.6.0/std/#std;os.read
I can't find a .readlines() style function in the zig standard library. You'll have to write your own loop to find the \n characters.
Below is a test case that shows how to create a file, write to it then open the same file and read its content.
const std = #import("std");
const testing = std.testing;
const expect = testing.expect;
test "create a file and then open and read it" {
var tmp_dir = testing.tmpDir(.{}); // This creates a directory under ./zig-cache/tmp/{hash}/test_file
// defer tmp_dir.cleanup(); // commented out this line so, you can see the file after execution finished.
var file1 = try tmp_dir.dir.createFile("test_file", .{ .read = true });
defer file1.close();
const write_buf: []const u8 = "Hello Zig!";
try file1.writeAll(write_buf);
var file2 = try tmp_dir.dir.openFile("test_file", .{});
defer file2.close();
const read_buf = try file2.readToEndAlloc(testing.allocator, 1024);
defer testing.allocator.free(read_buf);
try testing.expect(std.mem.eql(u8, write_buf, read_buf));
}
Check out fs package tests on Github or on your local machine under <zig-install-dir>/lib/fs/test.zig.
Also note that test allocator only works for tests. In your actual source code you need to choose an appropriate allocator.
Just starting with Deno, I am trying to figure out how to calculate a binary file checksum. It seems to me that the problem is not with the methods provided by the hash module of the standard library, but with the file streaming method and/or the type of the chunks feeding the hash.update method.
I have been trying a few alternatives, related to file opening and chunk types,with no success. A simple example is in the following:
import {createHash} from "https://deno.land/std#0.80.0/hash/mod.ts";
const file= new File(["my_big_folder.tar.gz"], "./my_big_folder.tar.gz");
const iterator = file.stream() .getIterator();
const hash = createHash("md5");
for await( let chunk of iterator){
hash.update(chunk);
}
console.log(hash.toString()); //b35edd0be7acc21cae8490a17c545928
This code compiles and runs with no errors, pity that the result is different from what I get running the functions of the crypto module provided by node and the md5sum provided by linux coreutils. Any suggestion ?
nodejs code:
const crypto = require('crypto');
const fs = require('fs');
const hash = crypto.createHash('md5');
const file = './my_big_folder.tar.gz';
const stream = fs.ReadStream(file);
stream.on('data', data=> { hash.update(data); });
stream.on('end', ()=> {
console.log(hash.digest('hex')); //c18f5eac67656328f7c4ec5d0ef5b96f
});
The same result in bash:
$ md5sum ./my_big_folder.tar.gz
$ c18f5eac67656328f7c4ec5d0ef5b96f ./my_big_folder.tar.gz
on Windows 10 this can be used:
CertUtil -hashfile ./my_big_folder.tar.gz md5
The File API isn't used to read a File in Deno, to do that you need to use the Deno.open API and then turn it into an iterable like this
import {createHash} from "https://deno.land/std#0.80.0/hash/mod.ts";
const hash = createHash("md5");
const file = await Deno.open(new URL(
"./BigFile.tar.gz",
import.meta.url, //This is needed cause JavaScript paths are relative to main script not current file
));
for await (const chunk of Deno.iter(file)) {
hash.update(chunk);
}
console.log(hash.toString());
Deno.close(file.rid);
import { crypto, toHashString } from 'https://deno.land/std#0.176.0/crypto/mod.ts';
const getFileBuffer = (filePath: string) => {
const file = Deno.openSync(filePath);
const buf = new Uint8Array(file.statSync().size);
file.readSync(buf);
file.close();
return buf;
};
const getMd5OfBuffer = (data: BufferSource) => toHashString(crypto.subtle.digestSync('MD5', data));
export const getFileMd5 = (filePath: string) => getMd5OfBuffer(getFileBuffer(filePath));
I am trying to import a SQL database into my Adobe Air iOS app. I have the invoke working and everything seems to work but the new database file can't be read. Below is my code.
function onInvoke(event:InvokeEvent):void{
if(event.arguments && event.arguments.length)
{
contentUri = event.arguments[0] as String;
file_db = new File(contentUri);
fs_db = new FileStream();
fs_db.addEventListener(Event.COMPLETE, import_db);
fs_db.openAsync(file_db, FileMode.READ);
}
}
My import function looks like this:
function import_db(event:Event):void{
fs_db.removeEventListener(Event.COMPLETE, import_db);
var fs:FileStream = new FileStream();
var myfile:File=File.applicationStorageDirectory.resolvePath("testDB.db");
var fileContent:String = fs_db.readUTFBytes(fs_db.bytesAvailable);
fs.open(myfile,FileMode.WRITE);
fs.writeUTFBytes(fileContent);
fs.addEventListener(Event.CLOSE, fileClosed);
fs.close();
function fileClosed(e:Event):void{
// do other stuff
}
}
Every thing seems to execute but when I try to connect to the database, I get SQL error:
Error #2044: Unhandled SQLErrorEvent:. errorID=3138, operation=open , message=Error #3138: File opened is not a database file.
Any guidance is appreciated
Figured it out, read the bytes into a bytearray and then into the file.
var mybytes:ByteArray=new ByteArray();
fs_db.readBytes(mybytes,0,fs_db.bytesAvailable);
fs.openAsync(myfile,FileMode.WRITE);
fs.writeBytes(mybytes,0,mybytes.length);
I have an iOS app that's using AS3 and AIR. I have external swfs downloading from a server and playing properly--all of this works perfectly fine.
I don't want the user to have to download these swfs every time they launch the app, though, so after the swf is downloaded the first time I want to save it to disk. That way I can load it from the local copy when I need it in the future, instead of downloading it again. I found this example online for saving files in AS3:
var file:File = File.applicationStorageDirectory.resolvePath("Swfs/" + "mySwfName" + ".swf");
var wr:File = new File(file.nativePath);
var stream:FileStream = new FileStream();
stream.open(wr, FileMode.WRITE);
stream.writeBytes(SWF_FILE_GOES_HERE, 0, SWF_FILE_DATA_LENGTH_GOES_HERE);
stream.close();
The problem is in the writeBytes line. The sample I found was for saving images to disk, and that line read like this:
stream.writeBytes(imageData, 0, imageData.length);
But I need to do this for a swf, not an image, and I'm not sure how to get the requisite data from my swf file. I've searched online for saving swf files, getting data from swf files, etc... But I haven't found anything. I need to get the swf's data and data length (I'm assuming this is a number of bytes?). Has anyone solved this problem before, or have a resource they can point me in the direction of?
UPDATE: Based on #LondonDrugs_MediaServices' comments, I figured out the writeBytes line:
stream.writeBytes(mySwf.loaderInfo.bytes, 0, mySwf.loaderInfo.bytesTotal);
This seems to work, in as much as it compiles and runs without errors. But when I try to grab the file and put it back into a movie clip, I get this error:
Error #2044: Unhandled IOErrorEvent:. text=Error #2035: URL Not Found.
Which implies that the file was not, in fact, saved correctly. When I print the file locations, however, they seem to be right! When I save the file to the applicationStorageDirectory:
/Users/MyName/Library/Preferences/com.appdir/Local Store/Swfs/mySwName.swf
And the filename when I try and load it out of storage and into a movie clip:
/Users/MyName/Library/Preferences/com.appdir/Local Store/Swfs/mySwName.swf
This is the code I'm using to try and load it back into a movie clip:
var videoFileName:String = "Swfs/" + ENVAR.currentVideoSelected + ".swf";
var videoFilePath:File = File.applicationStorageDirectory.resolvePath(videoFileName);
var inFileStream:FileStream = new FileStream();
trace("[Loading] filepath: ", videoFilePath.nativePath);
inFileStream.open(videoFilePath, FileMode.READ);
var fileContents:String = inFileStream.readUTFBytes(inFileStream.bytesAvailable);
inFileStream.close();
var req:URLRequest = new URLRequest(videoFilePath.nativePath);
var mLoader:Loader = new Loader();
mLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, onVideoLoadComplete);
mLoader.load(req);
And my onVideoLoadComplete function contains these lines:
var myMC:MovieClip = e.target.content as MovieClip;
addChild(myMC);
But I'm getting that error 2044 and it doesn't think the file exists. Can anyone spot the problem? Thanks!
You can get the raw bytes of a loaded swf file by using it's loaderInfo.bytes parameter. So for you example you could do this:
var file:File = File.applicationStorageDirectory.resolvePath("Swfs/" + key + ".swf");
var wr:File = new File(file.nativePath);
var stream:FileStream = new FileStream();
stream.open(wr, FileMode.WRITE);
stream.writeBytes(mySwf.loaderInfo.bytes, 0, mySwf.loaderInfo.bytesTotal);
stream.close();
Then to pull it back out into a MovieClip:
var videoFileName:String = "Swfs/" + ENVAR.currentVideoSelected + ".swf";
var videoFilePath:File = File.applicationStorageDirectory.resolvePath(videoFileName);
var inFileStream:FileStream = new FileStream();
inFileStream.open(videoFilePath, FileMode.READ);
var swfBytes:ByteArray = new ByteArray();
inFileStream.readBytes(swfBytes);
inFileStream.close();
var mLoader:Loader = new Loader();
var loaderContext:LoaderContext = new LoaderContext(false, ApplicationDomain.currentDomain);
loaderContext.allowCodeImport = true;
mLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, onVideoLoadComplete);
mLoader.loadBytes(swfBytes, loaderContext);
I'm struggling with a easy problem. I want to download an image from web using this code:
WebRequest requestPic = WebRequest.Create(#"http://something.com/" + id + ".jpg");
WebResponse responsePic = await requestPic.GetResponseAsync();
Now I wanted to write the WebResponse's stream in a StorageFile (eg. create a file id.jpg in the app's storage), but I haven't found any way to achieve that. I searched the web for it, but no success - all ways incompatible Stream types and so on.
Could you please help?
I have found the following solution, which works and is not too complicated.
public async static Task<StorageFile> SaveAsync(
Uri fileUri,
StorageFolder folder,
string fileName)
{
var file = await folder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);
var downloader = new BackgroundDownloader();
var download = downloader.CreateDownload(
fileUri,
file);
var res = await download.StartAsync();
return file;
}
You will need to read the response stream into a buffer then write the data to a StorageFile. THe following code shows an example:
var fStream = responsePic.GetResponseStream();
var file = await ApplicationData.Current.LocalFolder.CreateFileAsync("testfile.txt");
using (var ostream = await file.OpenStreamForWriteAsync())
{
int count = 0;
do
{
var buffer = new byte[1024];
count = fStream.Read(buffer, 0, 1024);
await ostream.WriteAsync(buffer, 0, count);
}
while (fStream.CanRead && count > 0);
}
That can be done using the C++ REST SDK in Windows Store Apps. It's explained by HTTP Client Tutorial.