I have a problem but I don't know how to solve it.
I reading a file from s3, then I save it to a folder(downloads). After that, I read the file that I saved in the folder (that I saved in downloads) and re-size it + save it in a different folder with a different name (resized).
Then, I want to read again this file in order to upload it again in its the new size but when I try to do that it throws an error that there is no such file in this directory but when I check it in my folder it dose.
My guess it's trying to read before the image is written in the new folder (resized)
How can I fix it?
update
so accroding to commits this is what I did but it disen't print out anything in fs.readFileAsync.
Why?
var image = new ImageResize(__dirname +'/../downloads/'+ hash + '.png');
image.smartResizeDown({
width: 200,
height: 200
}).then(function () {
image.stream(function (err, stdout, stderr) {
var writeStream = fs.createWriteStream(__dirname +'/../resized/'+ hash + 'resize.png');
stdout.pipe(writeStream);
}).then(function(){
fs.readFileAsync('C:/Users/user/Desktop/cloud/new/resized/'+hash+'resize.png', function(error, buf){
if(error)
console.log(error);
else
console.log('yay');
});
});
});
var image = new ImageResize(__dirname +'/../downloads/'+ hash + '.png');
image.smartResizeDown({
width: 200,
height: 200
})
.then(function () {
return new Promise(function(resolve, reject) {
image.stream(function (err, stdout, stderr) {
var writeStream = fs.createWriteStream(__dirname +'/../resized/'+ hash + 'resize.png');
stdout.pipe(writeStream);
resolve();
})
});
})
.then(function(){
fs.readFileAsync('C:/Users/user/Desktop/cloud/new/resized/'+hash+'resize.png', function(error, buf) {
if(error)
console.log(error);
else
console.log('yay');
});
return null;
});
Assuming bluebird object is in Promise named variable.
Related
Trying to create a new csv file in a directory.
I want to store the data of a variable inside that csv file:
handleRequest(req, res) {
var svcReq = req.body.svcReq;
var csvRecData = JSON.stringify(req.body);
console.log("DATA WE ARE GETIING IS: " + csvRecData);
if (svcReq == 'invDetails') {
var checking = fs.writeFile('../i1/csvData/myCsvFile.csv', csvRecData, function (err) {
if (err) throw err;
console.log("Saved! got the file");
console.log("Checking csvData:" + checking);
});
}
}
I don't see any errors in the console or terminal but the file is not generated. What is my issue?
The path in writeFile should be pointed correctly..you cannot simply use "../il/csv" from your current file.First check your current directory using path.
1)Install path npm module
2)
var path = require('path');
var fs = require('fs');
console.log(path.join(__dirname))
fs.writeFile((path.join(__dirname)+"/test123.csv"), "Sally Whittaker,2018,McCarren House,312,3.75!", function(err) {
if(err) {
return console.log(err);
}
console.log("The file was saved!");
});
I have a root directory say "A" inside this directory i am having lots of directories say "1","2","3","4","5"........ and in all these subdirectories i have single file called cucumber.json. All i want to do is read the cucumber.json file and get the accumulated result. How can i achieve this using node js.
In the below screen shot my root directory is "cucumber" and inside that i have lot of sub directories. All these sub directories contains a single file named cucumber.json.
Are there any dedicated node package which can make my work easy.
Let me know if any further info is required.
Hi there please try the following (javascript):
// Require filesystem package for IO operations
var fs = require('fs');
// Put the path you are looking for here
var path = "d:\\nodef";
//Call the function defined below
recursiveloop(path, function(err,result){
/* begin processing of each result */
// For each file in the array
for(i=0;i<result.length;i++)
{
//Write the name of the file
console.log('Processing: ' + result[i]);
//Read the file
fs.readFile(result[i], 'utf8', function(err, data){
//If there is an error notify to the console
if(err) console.log('Error: ' + err);
//Parse the json object
var obj = JSON.parse(data);
//Print out contents
console.log('Name: ' + obj.name);
console.log('Position: ' + obj.position);
})
}
});
// Asynchronous function to read folders and files recursively
function recursiveloop(dir, done)
{
var results = [];
fs.readdir(dir, function(err, list){
if (err) return done(err);
var i = 0;
(function next() {
var file = list[i++];
if (!file) return done(null, results);
file = dir + '/' + file;
fs.stat(file, function(err, stat) {
if (stat && stat.isDirectory()) {
recursiveloop(file, function(err, res) {
results = results.concat(res);
next();
});
} else {
results.push(file);
next();
}
});
})();
});
}
I want to re size a uploaded image on nodejs and send it on via ftp.
Using nodejs, busboy, GraphicsMagick, and jsftp.
var uploadFile = function(dir, req, cb) {
req.busboy.on('file', function(fieldname, file, filename, encoding, mimetype) {
var imageMagick = gm.subClass({
imageMagick: true
});
console.log('Resizing file...');
console.log(filename);
imageMagick(file)
.resize(150, 150)
.stream(function(err, stdout, stderr) {
if (err)
console.log(err);
var i = [];
stdout.on('data', function(data) {
console.log('data');
i.push(data);
});
stdout.on('close', function() {
console.log('close');
var image = Buffer.concat(i);
console.log(image.length);
console.log(image);
ftp.put(image, filepath, function(hadError) {
if (!hadError) {
filename = config.one.filepath + dir + "/" + filename;
cb(null, filename);
} else {
console.log(hadError);
cb(hadError, 'Error');
}
});
});
});
});
req.pipe(req.busboy);
};
The output is now:
Resizing file...
100-0001_IMG.JPG
close
0
<Buffer >
On ftp server side I get a 0 bytes file and also never doing a cb.
I found this two questions but couln't make it work for me:
Question 1
Question 2
I guess there must be something wrong with my file I gave to gm because "data" is never written to the console.
File it self is fine since I managed to upload a unresized file to the ftp server.
I appreciate every help!
Thx
Firstly you can check your stream for errors:
stdout.on('error', function(err) {
console.log(err);
});
So if there is an error related to imageMagick it can be a mismatching of imageMagic binary and node-imagemagick library
Trying to allow users to upload image files to the Node.js server in a MEAN Stack application. I am using ng-file-upload for the client side angular directive. That seems to be working good enough. I run into an error when I pass the image to the server.
I use an API route to handle the work on the server side. The server will be responsible for saving the file to disk with node-multiparty module. It seems to hit route but when it tries to emit a close event I get the error. throw new Error('"name" and "value" are required for setHeader().'
The file I want is in my temp folder but it doesn't get saved to the target directory on my server plus I get the header error after the file should have been saved. So I need to stop the error and save the file with fs.rename() to the target image directory.
Here is the code that is breaking.
file api.js
// router to save images
router.route('/img/upload')
.post(function (req, res) {
console.log("image upload hits the router")
var options = {};
var count = 0;
var form = new multiparty.Form(options);
//save file to disk
form.on('file', function (name, file) {
var uploadDirectory = 'img/user/profile/';
var oldPath = file.path;
var newPath = uploadDirectory + file.originalFilename;
fs.rename(oldPath, newPath, function (err) {
if (err) throw err;
console.log('renamed complete');
});
});
// Close emitted after form parsed
form.on('close', function () {
console.log('Upload completed!');
res.setHeader('text/plain'); // Here is the line that gives an error.
res.end('Received ' + count + ' files');
});
// Parse req
form.parse(req);
});
So this is what I got to work for me
The actual line that gave me an error was setHeaders. It appears I needed to put the name and value as strings separated by a comma. This works perfectly for me now. I hope it saves everyone time coding.
// post
.post(function (req, res) {
var options = {};
var count = 0;
var form = new multiparty.Form(options);
form.on('error', function (err) {
console.log('Error parsing form: ' + err.stack);
});
//save file to disk
form.on('file', function (name, file) {
var uploadDirectory = '/img/user/profile/';
var oldPath = file.path;
var newPath = uploadDirectory + file.originalFilename;
fs.rename(oldPath, newPath, function (err) {
if (err) throw err;
console.log('renamed complete');
});
});
// Close emitted after form parsed
form.on('close', function () {
console.log('Upload completed!');
res.setHeader('Content-Type', 'text/plain');
res.end('Received ' + count + ' files');
});
// Parse req
form.parse(req);
});
I can't think of an elegant solution. But, what would be the best way to process an HTML file, modify it and save it back using a script on the command line? I want to basically run this script, proving the HTML file as an argument, add a data-test=<randomID> into every <div> element, and save it back into the file. I was thinking I could write a JavaScript script to execute with node but am not sure how I would get the contents of the provided file, or what to store the content as. Thanks for any pointers.
Solved with jsdom (thanks for the tip, user1600124):
var jsdom = require("jsdom"),
fs = require('fs');
if (process.argv.length < 3) {
console.log('Usage: node ' + process.argv[1] + ' FILENAME');
process.exit(1);
}
var file = process.argv[2];
fs.readFile(file, 'utf8', function(err, data) {
if (err) throw err;
jsdom.env(
data,
["http://code.jquery.com/jquery.js"],
function (errors, window) {
var $ = window.jQuery;
$("p, li").each(function(){
$(this).attr("data-test", "test");
});
$(".jsdom").remove();
console.log( window.document.doctype + window.document.innerHTML );
var output = window.document.doctype + window.document.innerHTML;
fs.writeFile(file, output, function(err) {
if (err) throw err;
console.log('It\'s saved!');
});
});
});