Opening a file returns ErrorKind::Other 'Error: Os, code: 20, message: "Not a directory"' - file-io

I'm trying to open a file, and if it doesn't exist create it. But for some reason I'm getting an error of ErrorKind::Other with the message "Not a directory". Here is the full error I'm getting:
thread 'main' panicked at 'Unknown error when opening file: Os { code: 20, kind: Other, message: "Not a directory" }', src/main.rs:53:17
Here is my code:
let mut filepath = std::env::current_exe()?;
filepath.push("days");
filepath.set_extension("toml");
let mut file = match File::open(filepath.clone()) {
Ok(f) => f,
Err(e) => match e.kind() {
ErrorKind::NotFound => {
{
let mut create_file = File::create(filepath.clone());
create_file.write_all(...); // Dummy data
}
File::open(filepath.clone())?
},
_ => {
panic!("Unknow error when opening file: {:?}", e); // This is line 53
}
}
};
When I print the filepath to the console to check it I get "/mnt/c/Projects/Other/random/hmdict/target/debug/hmdict/days.toml", which is correct.
Does anyone know why I'm getting os error 20 "Not a directory"?
P.S I'm using Rust nightly-x86_64-unknown-linux-gnu with rustc version 1.46.0-nightly in WSL running on Windows 10 build 18363 Version 1909

The problem is push creates a seperate path. If your executable location was <what_ever>/hmdict, your code creates a path <whatever>/hmdict/days.toml. Obviously, this path doesn't exist because hmdict is a executable file and not a directory.

Related

AWS lambda function through terraform - Could not unzip uploaded file. Please check your file, then try to upload again

I am using terraform to create lambda function and already have zip package in S3. But I get below error:
RespMetadata: {
StatusCode: 400,
RequestID: "fa9b0e8b-02a6-4eaf-81ae-bf30fc6a1153"
},
Message_: "Could not unzip uploaded file. Please check your file, then try to upload again.",
Type: "User"
}
My code looks as below:
resource "aws_lambda_function" "test_lambda" {
s3_bucket = "bucket_name"
s3_key = "lambda.zip"
function_name = "Function_Test"
role = aws_iam_role.test_lambda_role.arn
handler = "config.lambda_handler"
runtime = "python3.8"
timeout = 180
vpc_config {
subnet_ids = ["subnet-123"]
security_group_ids = ["sg-123"]
}
environment {
variables = {
LOG_LEVEL = "DEBUG"
host = "https://abc:9098"
}
}
}
recently had the same issue with terraform. terraform expects the extension of filename to be a zip and not a python code/extension. the extension of "filename" was .py instead of .zip for me it worked fine when I used the correct extension.

s3Zip getting error - cannot read property of null

I have an expressjs back end and I'm trying to download/stream pdfs from s3 to a zip file. This is the error in the Heroku log:
TypeError: Cannot read property 'on' of null
at Object.s3Zip.archiveStream (/app/node_modules/s3-zip/s3-zip.js:49:6)
at Object.s3Zip.archive (/app/node_modules/s3-zip/s3-zip.js:33:24)
It was working on a localhost with "s3-zip": "^2.0.4" however I never deployed that version to heroku. Now I'm using "s3-zip": "^3.1.2"
also note, in my IDE the .archive statement is crossed out with a hint comment that a: Depreciated symbol used
public getZipFiles(req, res) {
const get_file = req.headers['pdfs'].split(',');
console.log("get file: ", get_file);
// first param is the zip file name
const zip_file_name = get_file.shift() + '.zip';
const user_downloads = downloadsFolder();
console.log(downloadsFolder()); // value is /tmp/
const output = fs.createWriteStream(join(user_downloads, zip_file_name));
// note: get_file is an array - ['file1.pdf', 'file2.pdf']
s3Zip
.archive({ region: aws_region, bucket: aws_bucket, debug: true }, '', get_file)
.pipe(output)
};
I expected to see the downloaded zip file, but got the error instead

Google Cloud Storage - Error during upload: gcs-resumable-upload.json renaming operation not permitted

I'm simply trying to follow this tutorial on how to upload files to gcs with Node and Express. But the following error keep causing my app to crash. Usually, I am able to upload one file without a problem in the first run. But I will get this error after running a few request, even with different file. When I try to upload, say 5, files at a time, this error cause my app to crash even in the first run. I see the process is trying to rename a file in the .config folder. Is it a normal behavior? If so, is there a work-around?
Window: v10.0.10586
Node: v4.3.1
Express: v4.13.1
Error: EPERM: operation not permitted, rename 'C:\Users\James Wang.config\configstore\gcs-resumable-upload.json.2873606827' -> 'C:\Users\James Wang.config\configstore\gcs-resumable-upload.json'
at Error (native)
at Object.fs.renameSync (fs.js:681:18)
at Function.writeFileSync as sync
at Object.create.all.set (C:\Users\James Wang\gi-cms-backend\node_modules\configstore\index.js:62:21)
at Object.Configstore.set (C:\Users\James Wang\gi-cms-backend\node_modules\configstore\index.js:93:11)
at Upload.set (C:\Users\James Wang\gi-cms-backend\node_modules\gcs-resumable-upload\index.js:264:20)
at C:\Users\James Wang\gi-cms-backend\node_modules\gcs-resumable-upload\index.js:60:14
at C:\Users\James Wang\gi-cms-backend\node_modules\gcs-resumable-upload\index.js:103:5
at Request._callback (C:\Users\James Wang\gi-cms-backend\node_modules\gcs-resumable-upload\index.js:230:7)
at Request.self.callback (C:\Users\James Wang\gi-cms-backend\node_modules\request\request.js:199:22)
at emitTwo (events.js:87:13)
at Request.emit (events.js:172:7)
at Request. (C:\Users\James Wang\gi-cms-backend\node_modules\request\request.js:1036:10)
at emitOne (events.js:82:20)
at Request.emit (events.js:169:7)
at IncomingMessage. (C:\Users\James Wang\gi-cms-backend\node_modules\request\request.js:963:12)
[nodemon] app crashed - waiting for file changes before starting...
UPDATE:
After setting {resumable: false} as suggested by #stephenplusplus in this post, I am no longer getting the "EPERM: operation not permitted" error.But, I start running into the { [ERROR:ETIMEDOUT] code: 'ETIMEDOUT', connection: false } error while trying to upload multiple files at a time with the largest file greater than 1.5mb. Other files get uploaded successfully.
For more information, I am able to upload files one by one when the files are no greater than ~2.5mb. If I try to upload 3 files at a time, I can only do so with files no greater than ~1.5mb.
Is the "Operation not permitted" issue as specified in the question a window specific thing, and does the timeout issue happen only after i set resumable = false?
I'm using express and multer with node.
This is the code I'm using now:
// Express middleware that will handle an array of files. req.files is an array of files received from
// filemulter.fields([{field: name, maxCount}]) function. This function should handle
// the upload process of files asychronously
function sendFilesToGCS(req, res, next) {
if(!req.files) { return next(); }
function stream(file, key, folder) {
var gcsName = Date.now() + file.originalname;
var gcsFile = bucket.file(gcsName);
var writeStream = gcsFile.createWriteStream({ resumable: false });
console.log(key);
console.log('Start uploading: ' + file.originalname);
writeStream.on('error', function(err) {
console.log(err);
res.status(501).send(err);
});
writeStream.on('finish', function() {
folder.incrementFinishCounter();
req.files[key][0].cloudStorageObject = gcsName;
req.files[key][0].cloudStoragePublicUrl = getPublicUrl(gcsName);
console.log('Finish Uploading: ' + req.files[key][0].cloudStoragePublicUrl);
folder.beginUploadNext();
});
writeStream.end(file.buffer);
};
var Folder = function(files) {
var self = this;
self.files = files;
self.reqFilesKeys = Object.keys(files); // reqFilesKeys is an array of keys parsed from req.files
self.nextInQuene = 0; // Keep track of the next file to be uploaded, must be less than reqFilesKeys.length
self.finishCounter = 0; // Keep track of how many files have been uploaded, must be less than reqFilesKeys.length
console.log(this.reqFilesKeys.length + ' files to upload');
};
// This function is used to initiate the upload process.
// It's also called in the on-finish listener of a file's write-stream,
// which will start uploading the next file in quene
Folder.prototype.beginUploadNext = function() {
// If there's still file left to upload,
if(this.finishCounter < this.reqFilesKeys.length) {
// and if there's still file left in quene
if(this.nextInQuene < this.reqFilesKeys.length) {
// upload the file
var fileToUpload = this.files[this.reqFilesKeys[this.nextInQuene]][0];
stream(fileToUpload, this.reqFilesKeys[this.nextInQuene], this);
// Increment the nextInQuene counter, and get the next one ready
this.nextInQuene++;
}
} else {
console.log('Finish all upload!!!!!!!!!!!!!!!!!!!!!!');
next();
}
};
Folder.prototype.incrementFinishCounter = function() {
this.finishCounter++;
console.log('Finished' + this.finishCounter + ' files');
};
var folder = new Folder(req.files);
// Begin upload with 3 streams
/*for(var i=0; i<3; i++) {
folder.beginUploadNext();
}*/
//Upload file one by one
folder.beginUploadNext();
}
I had the same issue with bower .. Run the following command: bower cache clean --allow-root
if this does not solve the problem, try after disabling anti virus.

Unable to load SWF from application storage directory

While publishing my AIR application(CurrentFile), I have also included chatFile.swf with the installation files.
In my AIR settings panel [AIR 3.7 for Desktop], under 'Include Files' I have the following:
CurrentFile.swf
CurrentFile-app.xml
chatFile.swf
Here is the AS3 code in my CurrentFile.swf:
import flash.net.URLRequest;
import flash.events.Event;
import flash.display.Loader;
import flash.filesystem.File;
var chatLoaderWindow:Loader;
function loadchat(m:MouseEvent):void
{
chatLoaderWindow = new Loader();
chatLoaderWindow.contentLoaderInfo.addEventListener(Event.COMPLETE, chatLoadComplete);
chatLoaderWindow.contentLoaderInfo.addEventListener(Event.INIT, chatInitLoad);
chatLoaderWindow.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, chatErrorLoad);
chatLoaderWindow.contentLoaderInfo.addEventListener(HTTPStatusEvent.HTTP_STATUS, chatHttpStatus);
myclip.chatwindow.addChild(chatLoaderWindow);
var f:File = File.applicationStorageDirectory.resolvePath("chatFile.swf");
chatLoaderWindow.load(new URLRequest(f.url));
tracebox.text = "Chat URL" + f.url;
}
function chatLoadComplete(e:Event):void
{
tracebox.text = "chat loaded";
}
function chatErrorLoad(io:IOErrorEvent):void
{
tracebox.text = "chat IO Error: "+io;
}
function chatInitLoad(i:Event):void
{
tracebox.text = "chat INIT";
}
function chatHttpStatus(e:HTTPStatusEvent):void
{
tracebox.text = "chat Http"+e;
}
myclip.chatbut.addEventListener(MouseEvent.CLICK,loadchat);
/*
Output:
chat IO Error: [IOErrorEvent type="ioError" bubbles=false cancelable=false eventPhase=2 text="Error #2035" errorID=2035]
EDIT: I figured it out. It was really simple
This is not required:
var f:File = File.applicationStorageDirectory.resolvePath("chatFile.swf");
chatLoaderWindow.load(new URLRequest(f.url));
Insert this:
chatLoaderWindow.load(new URLRequest("app:/chatFile.swf"));
So now my question is:
What is the purpose of File.applicationStorageDirectory.resolvePath?
There are two directories here. One is the "application" directory, where your install files are placed. One is the "application-storage" directory, which is a convenient place to write files to at runtime. To access these directories you can either use the File.resolvePath() function or use the URI-scheme shortcuts, app: or app-storage:. In your initial attempt, you were just looking in the wrong directory for your file.
File.applicationStorageDirectory.resolvePath("somefile.swf").url will equal "app-storage:/somefile.swf"
File.applicationDirectory.resolvePath("somefile.swf").url will equal "app:/somefile.swf"
The application directory is where your app was installed. The app storage directory is a folder your app can save files to.
resolvePath() returns a file object. You can use it for purposes other than getting the cross-platform url for the file location, such as fileObj.exists and fileObj.parent.createDirectory(). fileObj.url is just the url you would use with URLLoader to access the file in a platform-independent manner.

CakePHP 2.0 + Notice (8): Undefined index: Upload [APP/Controller/UploadsController.php, line 32]

Im using 000webhost as a way to host my portfolio of websites. However Im getting this error thrown in which doesn't happen to me on localhost.
Notice (8): Undefined index: Upload [APP/Controller/UploadsController.php, line 32]
This is the code it seems to be referring to,
public function add() {
$this->render();
if($this->request->is('post')){
$file = $this->request->data['Upload']['file'];
if($this->Upload->save($this->data) && move_uploaded_file($file['tmp_name'],APP.'webroot/files/uploads'.DS.$this->Upload->id.'.mp4'))
{
$this->Session->setFlash('<p class="uploadflash">The upload has been saved</p>', true);
$this->redirect(array('controller'=>'Uploads', 'action' => 'watch', $this->Upload->id));
} else {
$this->Session->setFlash('<p class="loginerror">The upload could not be saved, mp4 files can be saved only.</p>', true);
}
}
}
Any ideas as to why this is happening?
Also in addition my Elements are not showing up on this online hosting either?
I get thrown this error on the page
Element Not Found: Elements/uploads/recentuploads.ctp
Does anyone else seem to have this problem??
Upon further inspection I have found that the server does not allow file upload sizes to exceed 2mb, in this instance PHP throws the error above.