I have a path in the file system, say
/home/user/lannister/wines/red/knowthings
Inside lannister folder, my nodejs code resides. What the code is supposed to do, is, to create a blank file called debtslist.txt which should be located inside knowthings folder, so that the file path becomes
/home/user/lannister/wines/red/knowthings/debtslist.txt
I tired several ways of doing it, that include:
const filePath = 'wines/red/knowthings/debtslist.txt';
fs.openSync(filePath, 'w');
and
const filePath = 'wines/red/knowthings/debtslist.txt';
fs.writeFile(filePath, '', function (err) {
if (err) throw err;
});
But every time I am getting this error:
Error
Error: ENOENT: no such file or directory, open 'wines/red/knowthings/debtslist.txt'
Am I specifying the path in const filePath in a wrong way?
Related
I am trying to run a simple script to convert a PDF --> PNG using gs package. The code runs successfully runs when deployed to Firebase Cloud Functions but I test it locally using the firebase functions:shell command it appears to run w/o error but the output file (the .png) is missing and I get the following error:
Error: ENOENT: no such file or directory, open '/var/folders/sr/pjwr5d0s75bgzvx4xgcdcylw0000gp/T/*****/-***********.png'
The path is correct, but the .png file is missing but the pdf is there and gs outputted no errors. I even tried changing the path from os.tmpdir() to a specific path on my desktop (Mac) and it still failed to create the png file.
The same code when deployed to firebase runs fine.
Here is my gs code (I have ommitted the CF code and invocation code):
//============== Ghostscript
//Conver PDF -> PNG
console.log('gs - starting');
gs()
.batch()
.nopause()
.option('-r' + 50 * 2)
.option('-dDownScaleFactor=2')
.executablePath('lambda-ghostscript/bin/./gs')
// .device('png16m')
.device('pngalpha')
.output(outputPath)
.input(pdfPath)
.exec(function (err, stdout, stderr) {
if (!err) {
console.log('gs executed w/o error');
console.log('stdout',stdout);
console.log('stderr',stderr);
console.log('output saved to: ', outputPath);
resolve(outputPath);
} else {
console.log('gs error:', err);
reject();
}
});
})
I have no idea why it doesn't work locally but does when deployed. My path input is correct and the output is path.join(os.tmpdir(), '****.png');
Edit Output from GS in console:
> gs executed w/o error
> stdout
> stderr
> output saved to: /var/folders/sr/pjwr5d0s75bgzvx4xgcdcylw0000gp/T/*******/*********.png
For some reason, I need to modify my mongodb with brute force.
the expected data is in a file, and I need to update the mongodb's value by the read-out file stream. with node.js' help, I generate codes like this,
const fs = require('fs');
fs.open('./f.csv', 'r', (err, fd) => {
if(!err) {
fs.readFile('./server/f.csv', 'utf8', (err,data)=>{console.log(data);});
}
});
But, now I have a difficulty to find the file. the execution throws an error:
{ Error: ENOENT: no such file or directory, open './f.csv' errno: -2, code: 'ENOENT', syscall: 'open', path: './f.csv' }
I have tried to locate the file in the Meteor's public folder or server folder, which is also Meteor's backend, but the efforts are in vain. So how to make the codes find the file on Meteor's backend?
Any suggestion is welcome.
Easiest solution is to put the file in /private and access it using the Assets module:
https://docs.meteor.com/api/assets.html
Example: If you put the file in /private/f.csv
const data = Assets.getText('f.csv');
console.log(data)
// ... Do something with that data
I am using this block of code to create and write a new directory and a file.
I just started to learn nodejs
var lib = {};
lib.baseDir = path.join(__dirname,'/../.data/');
lib.create = function(dir,file,data,callback){
fs.open(lib.baseDir+dir+'/'+file+'.json', 'wx', function(err, fileDescriptor){
if(!err && fileDescriptor){
var stringData = JSON.stringify(data);
// Write to file and close it
fs.writeFile(fileDescriptor, stringData,function(err){
if(!err){
fs.close(fileDescriptor,function(err){
if(!err){
callback(false);
} else {
callback('Error closing new file');
}
});
} else {
callback('Error writing to new file'+'lib.baseDir');
}
});
} else {
callback(err);
}
});
};
but I am repeatedly getting the error
{ Error: ENOENT: no such file or directory, open 'C:\Users\Jawahr\Documents\GitHub\node-api\.data\test\newFile.json'
errno: -4058,
code: 'ENOENT',
syscall: 'open',
path: 'C:\\Users\\Jawahr\\Documents\\GitHub\\node-
api\\.data\\test\\newFile.json' }
calling this library in a index.js as
var _data = require('./lib/data');
_data.create('test','newFile', {"asdksadlk" : "asldj"} ,function(err) {
console.log('this was the error ',err);
});
I've been stuck here for a while, is it because the pathname and filename contained the part "C:" which has colon a reserved char in windows 10, if it is the problem how to solve this.
using windows 10 and NodeJs 8.6.
Can you try this -
fs.open(lib.baseDir+dir+'/'+file+'.json', 'w', function(err, fileDescriptor){
It looks like 'wx' throws an error if file exists -
'w' - Open file for writing. The file is created (if it does not exist) or truncated (if it exists).
'wx' - Like 'w' but fails if the path exists.
'w+' - Open file for reading and writing. The file is created (if it does not exist) or truncated (if it exists).
'wx+' - Like 'w+' but fails if the path exists.
Referred from here
Looks like your put non-existing or non-accessible path to your file. Look:
fs.open('/path/is/not/exists/xx.js','wx',(err,fd)=>{
if (err) {
console.log(err.message);
}
});
and got
Error: ENOENT: no such file or directory, open '/path/is/not/exists/xx.js'
In case when file is already exists you will got something like Error: EEXIST: file already exists, open '...'
And last, but not least. Instead of lib.baseDir+dir+'/'+file+'.json' better solution is use path.join(lib.baseDir,dir,file+'.json') from path module
Add a check for directory or create before fs.open
if (!fs.existsSync(dir)){
fs.mkdirSync(dir);
}
Then the rest of your code will work. as fs.open only creates file if it doesn't exist, it does not create directory
ENOENT - but my file is just in the same directory ...
Hi all I try to sent a file, birds.mp3, to my Google Drive using API. The file got to be reached by a function to be sent.
Despite that the file I try to send is just in the same folder that the code concerned, my console return me :
events.js:183
throw er; // Unhandled 'error' event
^
Error: ENOENT: no such file or directory, open './birds.mp3'
Here my tree :
-- folder
|-- birds.mp3
|-- quickstart.js
Here my quickstart.js
module.exports.insertDrive = function (req) {
console.log("callback reached.")
var url = req.body.url;
var folderId = 'id';
var fileMetadata = {
'name': req.body.word,
parents: "id"
};
var media = {
mimeType: 'audio/*',
body: fs.createReadStream("./birds.mp3") // PATH FUNCTION HERE
};
drive.files.create({
resource: fileMetadata,
media: media,
fields: 'id'
}, function (err, file) {
if (err) {
// Handle error
console.error(err);
} else {
console.log('File Id: ', file.id);
}
})};
I can't figure out why my file can't be reached. I have try several tricks like path.resolve and all, I have try to push my birds.mp3 in several folder if any, but that have failed.
Thanks.
If you're trying to load a file from the same directory as the current module and pass that to the Google API, then use __dirname instead of ./. The ./ uses the current working directory which will depend upon how the overall program was invoked and will not point at your module directory.
So, if the intended file is in the same directory as your module, then change this:
fs.createReadStream("./birds.mp3")
to this:
fs.createReadStream(path.join(__dirname, "birds.mp3"));
I can't for the life of me think of a way to do this. I've previously worked with importing csv files into js files, but for this challenge I've got to create a js file that executable from a shell with the data file passed as input.
Any ideas how can this be done?
~The challenge description~
The program must be executable from a shell and take the CSV file as input. For example:
node score_calculator.js data.csv
You can take the file path as command line argument when running your nodejs app like
node myScript.js pathToCsvFile
Now you'll have to get this path in your code as
var filePath = process.argv[2];
Now you can use this path to read your file as
fs.readFile(filePath, (err, data) => {
if (err) throw err;
console.log(data);
});
Read more about file handling in nodejs here
Hope this helps
Sounds like you are trying to figure out how to pass and read parameters
You could do node score_calculator.js data.csv
then in your js
const csv = process.argv[2];
However. If you are passing in parameters I would recommend using minimist then you can do
node score_calculator.js --file=data.csv
And you js file would be
const argv = require('minimist')(process.argv.slice(2));
const csv = argv.file;