I am trying to save a simple file to a directory other then my root directory, but it seems to error out when using a variable instead of a direct string.Has anyone tried using a variable or see if i am missing something.
Thanks
var procedures = "SomeString";
var moveTo = "C:/SavedFiles";
//////////////////
fs.writeFile(moveTo ,procedures, function (err) {
if (err) {
return console.log(err);
}
console.log("The file was saved!");
});`
Am I correct that "C:/SavedFiles" is a directory? Is so, then specify a file to write to like:
var moveTo = "C:/SavedFiles/myfile.txt";
// keep the rest the same
Not sure about the slashes though, not running Windows ATM.
So it looks like my error was due to a rouge loop above my code not posted. Sorry i didn't post the rest of the code
Related
I am trying to create a new JSON file. Whenever I try to use the writeFile function, it just says there is no such directory open.
This is the code I've tried.
fs.writeFile('./UserData/' + msg.author + ".json", JSON.stringify({firstSplitContent: firstSplit,secondSplitContent: secondSplit,thirdSplitContent: thirdSplit,fourthSplitContent: fourthSplit,fifthSplitContent: fifthSplit},null,4), err => {
if(err) throw err;
console.log("File is created successfully.")
});
Error: ENOENT: no such file or directory, open './UserData/<#301910353967710208>.json'
help would be appreciated. Yes I know that windows wont use those special characters. I switched it to author.id to remove.
fs.writeFile won't create any directories that don't already exist.
I suspect that the directory in your path, UserData, doesn't exist, which is why you are getting that error.
Otherwise, your path may be wrong. Since you are using a relative path, the code will look for the UserData folder in the working directory, ie. where the code is currently executing.
If the path is correct, try creating it first:
if(!fs.existsSync('./UserData') {
fs.mkdirSync('./UserData')
}
Or, you could use a package such as fs-extra that gives you the capability of creating any folders in the path that don't already exist.
This is probably the most relevant function to you, if you want to use fs-extra:
https://github.com/jprichardson/node-fs-extra/blob/master/docs/outputJson.md
You should follow the answer of Willianm but just one thing I noticed: You are trying to use msg.author in your file name, but that's an object (a really big object), you might want to consider changing it to message.author.id
I am using node js express. I am trying to access a text file located in the same directory of that js file. So the file structure goes like this
- ProjectFolder
|
- many modules and folders
- routes
|
- Index.js
- input.txt
The Simple code that i have tried is ,
var data = fs.readFile('~/IdeaProjects/Title/routes/input.txt');
console.log("Synchronous read: " + data.toString());
console.log("Program Ended");
I did try different paths but nothing works. for your information, I am using fedora as os.
The error i got was,
Error: ENOENT: no such file or directory, open '~/IdeaProjects/Title/routes/input.txt'
at Error (native)
Any suggestion about how to access that file so that i can both read and write the contents of the file , will be welcomed. Looking for detailed answer.
Node doesn't interpret some characters that have special meaning like ~ or shell variables like $HOME, so you will need to use something like path.resolve() to get an absolute path or use a relative path (e.g. IdeaProjects/Title/routes/input.txt).
Also, as #Gothdo pointed out, there is a discrepency in the filename which will cause issues on case-sensitive file systems.
You will also need to either change fs.readFile() to fs.readFileSync() or add a callback to fs.readFile() like so:
fs.readFile('~/IdeaProjects/Title/routes/input.txt', function(err, data) {
if (err) throw err;
console.log("Synchronous read: " + data.toString());
console.log("Program Ended");
});
I am trying to read the metadata tags from an mp4 file into my javascript using the node module mp4js. I followed the model provided on that page but with some issue.
I tried the following:
var mp4 = require('mp4js');
mp4({ file: 'small.mp4', type: 'local' }, function (err, tags) {
// tags now contains your MP4 tags
console.log('Tags: ' + tags)
$scope.mp4Tags = tags;
});
and I was met with Uncaught TypeError: Cannot read property 'join' of undefined
Does anyone know what I'm missing here? Could it be that the mp4 doesn't have any tags? I just googled "sample mp4" and downloaded something. It's my first time trying this module and I am pretty new to node.
I'm also open to other suggestions for reading mp4 metadata.
Thank you very much for your time and let me know if you need any additional from me.
EDIT 8.26.2015
Following Brad's suggestion, I tried the following code to read metadata from an mp4:
var child_process = require('child_process');
ls = child_process.spawn('ffmpeg/bin/ffprobe.exe', ['-print_format', 'json', 'out.mp4']);
ls.stdout.on('data', function (data) {
console.log('stdout: ' + data);
$scope.mp4data = data;
});
I created mp4.out by following this example for adding a title meta tag using ffmpeg from the command line. Here is a screenshot of my output. Here is the command I entered:
ffmpeg -i in.avi -metadata title="my title" out.flv
After running my app with the code above, the value stored in $scope.mp4data is a Native Buffer that looks like this. All I see are some numbers, but no metadata tags. How can I view the metadata such as the title that I set using the command above? Am I missing something in the arguments? Or maybe I should be looking at something other than data?
Thanks for the help. I may just post this as a new question since the focus has shifted.
EDIT: Solution
Here's where I landed thanks to Brad's help:
$scope.mp4data = "";
ls.stdout.on('data', function (data) {
$scope.mp4data = $scope.mp4data + data.toString();
});
ls.stdout.on('end', function (data) {
$scope.mp4data = JSON.parse($scope.mp4data);
});
works great for reading metadata from my mp4! Thanks Brad!
I recommend using FFprobe (from the FFmpeg project) to do this instead. It supports many containers, including MP4.
You can use ffprobe -print_format json to have it output JSON data that you can parse inside your Node.js app.
Some examples here: https://stackoverflow.com/a/8191228/362536
I'm trying to migrate a node project to run in the browser. The project (nevermind the reason for the moment) writes to a temporary file, using temp with code similar to this:
var temp = require('temp');
var fs = require('fs');
temp.open('helloworld.txt', function (err, info) {
if (err) {
console.log('Failed to open a temp file:', err);
return;
}
console.log('temp: ', info.path);
fs.writeFile(info.path, 'Hello World!', function (err2) {
if (err2) {
console.log('Failed to write to a temp file:', err2);
return;
}
});
});
When running the browserified code I get the following error:
Uncaught TypeError: undefined is not a function
for the following line:
fs.open(filePath, RDWR_EXCL, 0600, function(err, fd) {
which is called by temp.open.
I'm very much aware you cannot write files using plain ol' javascript in the browser, but I was wondering if browserify have some replacement for that, especially since we're talking about a temp file.
I found browserify-fs, and tried:
browserify -r fs:browserify-fs my-example.js -o bfied.js
but I get the exact same error. I tried to replace require('fs') with require('browserify-fs') but this resulted in a similar error as well (I of course installed browserify-fs module..)
Any suggested solution would be appreciated :) If this type of migration is not possible, I'd also be glad to know..
Thanks!
I stumbled across this post as I think I was trying to do pretty much the exact same thing as you. I am not sure where you got to with this, but I found that when using browserify-fs, you cannot access files outside the sandboxed state of the browser.
So when trying...
var fs = require('broserify-fs);
fs.read('hello.txt', 'utf8' ....
I got the same error as you, but when doing this...
fs.mkdir('/home', function() {
fs.writeFile('/home/hello-world.txt', 'Hello world!\n', function() {
fs.readFile('/home/hello-world.txt', 'utf-8', function(err, data) {
console.log(data);
});
});
});
Everything worked fine (using just temporary files I think).
I am super new to this so I'm not sure what the best approach is. I imagine you either want to run a Node.js server locally and issue ajax commands to it to perform read/write operations, or investigate the HTML5 file system stuff - this looks like a good article - http://www.html5rocks.com/en/tutorials/file/dndfiles/
Hope that's some help (sorry you've had to wait 2 months for an answer ;) It was serendipitous I happened to stumble across your question and my heart sank when there were no answers)
Tom
I'm using Express.js and have a route to upload images that I then need to resize. Currently I just let Express write the file to disk (which I think uses node-formidable under the covers) and then resize using gm (http://aheckmann.github.com/gm/) which writes a second version to disk.
gm(path)
.resize(540,404)
.write(dest, function (err) { ... });
I've read that you can get a hold of the node-formidable file stream before it writes it to disk, and since gm can accept a stream instead of just a path, I should be able to pass this right through eliminating the double write to disk.
I think I need to override form.onPart but I'm not sure where (should it be done as Express middleware?) and I'm not sure how to get a hold of form or what exactly to do with the part. This is the code skeleton that I've seen in a few places:
form.onPart = function(part) {
if (!part.filename) { form.handlePart(part); return; }
part.on('data', function(buffer) {
});
part.on('end', function() {
}
}
Can somebody help me put these two pieces together? Thanks!
You're on the right track by rewriting form.onPart. Formidable writes to disk by default, so you want to act before it does.
Parts themselves are Streams, so you can pipe them to whatever you want, including gm. I haven't tested it, but this makes sense based on the documentation:
var form = new formidable.IncomingForm;
form.onPart = function (part) {
if (!part.filename) return this.handlePart(part);
gm(part).resize(200, 200).stream(function (err, stdout, stderr) {
stdout.pipe(fs.createWriteStream('my/new/path/to/img.png'));
});
};
As for the middleware, I'd copypaste the multipart middleware from Connect/Express and add the onPart function to it: http://www.senchalabs.org/connect/multipart.html
It'd be a lot nicer if formidable didn't write to disk by default or if it took a flag, wouldn't it? You could send them an issue.