i'm trying to fix a bug with my twitter bot, basically, there is an array with all the filenames of the folder, then selects one randomly and posts it, but sometimes posts the same image again, how can i fix it?
here is the code
var fs = require('fs'),
path = require('path'),
Twit = require('twit'),
set = require(path.join(__dirname, 'set.js'));
//array of files
files_memes = require(path.join(__dirname, 'files.js'))
var currentdate = new Date();
var upl = "Subido: "
+ currentdate.getHours() + ":"
+ currentdate.getMinutes()+ " hs.";
var setMin = 10;
var T = new Twit(set);
function random_file(){
var allFiles = (files_memes)//array
return allFiles[Math.floor(Math.random() * allFiles.length)];
}
var filename = (random_file());
var imgPATH = path.join(__dirname, '/memestorage/queue/' + filename);
//image selection and upload
function upload_random_image(){
console.log('Opening file...');
var image_path = imgPATH,
b64content = fs.readFileSync(image_path, { encoding: 'base64' });
console.log('Uploading file...');
T.post('media/upload', { media_data: b64content }, function (err, data, response) {
if (err){
console.log('ERROR');
console.log(err);
}
else{
console.log('File loaded!');
T.post('statuses/update', {
media_ids: new Array(data.media_id_string)
},
function(err, data, response) {
if (err){
console.log('Error!');
console.log(err);
}
else{
console.log('Tweeted!');
console.log(upl);
console.log('Next tweet in ' + setMin + ' min.');
}
}
);
}
});
}
//timer
setTimeout(
upload_random_image,
0
);
setInterval(
upload_random_image,
1000*10
);
I've tried with
...
var filename = (random_file());
var pfile = ("posted"+random_file());
var imgPATH = path.join(__dirname, '/memestorage/queue/' + filename);
var postedFile = path.join(__dirname, '/memestorage/posted/' + pfile);
fs.rename(imgPATH, postedFile, function(err) {
if ( err ) console.log('ERROR: ' + err);
});
//image selection and upload
function upload_random_image(){
console.log('Opening file...');
var image_path = imgPATH,
b64content = fs.readFileSync(imgPATH, { encoding: 'base64' });
...
But posts the same image over and over again, or sometimes gives this error message:
fs.js:640
return binding.open(pathModule._makeLong(path), stringToFlags(flags), mode);
^
Error: ENOENT: no such file or directory, open 'D:\memesbot\memestorage\queue\645 (2).jpg'
at Error (native)
at Object.fs.openSync (fs.js:640:18)
at Object.fs.readFileSync (fs.js:508:33)
at Timeout.upload_random_image [as _onTimeout] (D:\memesbot\memes.js:29:23)
at ontimeout (timers.js:365:14)
at tryOnTimeout (timers.js:237:5)
at Timer.listOnTimeout (timers.js:207:5)
Hope someone can help me, thanks.
Code seem to be generating random file at start (var filename = (random_file());) but not at run of upload_random_image().
So, file is selected randomly one and upload_random_image is called multiple times with setInterval
Solution:
Move below line inside the method upload_random_image
var filename = (random_file());
var imgPATH = path.join(__dirname, '/memestorage/queue/' + filename);
Related
I have to archive a directory in which log file are present(File names are in a format as i.e 2017-12-06.log).I have to archive all files except 2017-12-06.log.
I have a logs directory where all log files are present and a script create-zip.js. When I run following script with node create-zip.js, It creates directories as /archive/<year>/<month_name> and saves here logs.zip folder.
Everything is fine except when I extract logs.zip, my archived log files are found inside /archive/<year>/<month_name>/home/hotam/nodejs_archive_example/logs but I want these files inside /archive/<year>/<month_name>. I googled a lot but couldn't find solution. Thanks in advance.
I have following script(create-zip.js):
'use strict';
var fs = require('fs'),
path = require('path'),
archiver = require('archiver'),
currDate = new Date(),
year = currDate.getFullYear(),
month = currDate.toLocaleString("en-us", { month: "long" }),
dir = path.join(__dirname + '/archive/' + year + '/' + month),
ignoredFile = currDate.getFullYear()+'-'+('0' + (currDate.getMonth() + 1)).slice(-2)+'-'+('0' + currDate.getDate()).slice(-2)+'.log';
//Function to create directories recursively
exports.createDir = function (dir) {
const splitPath = dir.split('/');
splitPath.reduce(function (dirPath, subPath) {
let currentPath;
if (subPath != '.') {
currentPath = dirPath + '/' + subPath;
if (!fs.existsSync(currentPath)) {
fs.mkdirSync(currentPath);
}
} else {
currentPath = subPath;
}
return currentPath
}, '');
};
exports.createDir(dir);
var output = fs.createWriteStream(path.join(dir, 'logs.zip'));
var archive = archiver('zip', {});
var logPath = __dirname + '/logs';
output.on('close', function () {
if (fs.existsSync(logPath)) {
fs.readdirSync(logPath).forEach(function (file, index) {
var curPath = logPath + "/" + file;
if (!fs.lstatSync(logPath).isFile()) {
// delete file
if(!(file == ignoredFile)) {
fs.unlinkSync(curPath);
}
}
});
}
});
output.on('end', function () {
console.log('Data has been drained');
});
archive.on('warning', function (err) {
if (err.code === 'ENOENT') {
console.log(err);
} else {
// throw error
console.log(err);
throw err;
}
});
archive.on('error', function (err) {
logger.error(err);
throw err;
});
archive.pipe(output);
//ignoring 2017-12-06.log
archive
.glob(__dirname + '/logs/**', {
ignore: [__dirname + '/logs/'+ignoredFile]
})
.finalize();
I got the solution of this scenario. I changed archive.glob() and it worked for me.
`//ignoring 2017-12-06.log
archive
.glob('./logs/**/*', {
ignore: ['./logs/**/*' + ignoredFile]
})
.finalize();`
i am trying to get the file information from a file on my Amazon S3 server using the aws-sdk node module.
What i want to get out is the file name, file type and size.
I have attempted the following methods without luck:
s3.headObject(params, function (err, data) {
if (err) {
console.log(err, err.stack)
}
else {
d.resolve(data);
}
});
And
s3.getObject(params, function (err, data) {
if (err) {
console.log(err, err.stack)
}
else {
d.resolve(data);
}
});
Looking through their documentation i cant seem to find any other method that will give me the information i need.
So my question to you is how do i get the above information?
Here is the code to get the file name, size and content-type of all the objects present in a bucket.
Change the bucket name
Load your access keys from config.json accordingly
Code:-
var AWS = require('aws-sdk');
// Load credentials and set region from JSON file
AWS.config.loadFromPath('./config.json');
// Create S3 service object
s3 = new AWS.S3({ apiVersion: '2006-03-01' });
var bucketName = 'yourBucketName';
var params = {
Bucket: bucketName
};
var headParams = {
Bucket: bucketName
};
listAllKeys();
function listAllKeys() {
s3.listObjectsV2(params, function (err, data) {
if (err) {
console.log(err, err.stack); // an error occurred
} else {
var contents = data.Contents;
contents.forEach(function (content) {
//console.log(JSON.stringify(content));
headParams["Key"] = content.Key;
s3.headObject(headParams, function (err, headObjectData) {
if (err) {
console.log(err, err.stack);
} else {
console.log("1. File name :" + content.Key + ";" + " 2. File size :" + content.Size + ";" + " 3. Content-Type :" + headObjectData.ContentType);
}
});
});
if (data.IsTruncated) {
params.ContinuationToken = data.NextContinuationToken;
console.log("get further list...");
listAllKeys();
}
}
});
}
Sample output:-
1. File name :index.html; 2. File size :48; 3. Content-Type :text/html
s3.headObject works fine. You can find sample code below
let primaryBucket = primarys3bucketname;
var headParams = {
Bucket: primaryBucket,
};
let size = '';
headParams["Key"] = "/sample/path/to/filename.pdf";
s3.headObject(headParams).promise().then((headObjectData) => {
size = this.bytesToSize(headObjectData.ContentLength);
});
function bytesToSize(bytes) {
var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
if (bytes == 0) return '0 Byte';
var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
return Math.round(bytes / Math.pow(1024, i), 2) + ' ' + sizes[i];
};
Can someone give me a hand with converting the following code from console output to file output? I'm struggling with logging and the asynchronous nature of Node. The script works great in a console, but I'd like to pipe the sorted output into individual server sections within a file with STDERR going to another file.
var rexec = require('remote-exec');
var fs = require('fs');
var lineReader = require('line-reader');
var streamBuffers = require('stream-buffers');
var _ = require('lodash');
var conn_options = {
port: 22,
username: '*****',
privateKey: fs.readFileSync('R:/nodeJS/sshkey.priv')
}
// something that dumps out a bunch of data...
var cmds = ['df']
var filename = 'servers.txt';
lineReader.eachLine(filename,function(line,last,cb){
var buffer = new streamBuffers.WritableStreamBuffer();
var my_conn_options = _.clone(conn_options);
rexec(line,cmds,my_conn_options,function(err){
if (err) {
console.log(line, err);
} else {
console.log('>>>> Start: ' + line + '<<<<')
console.log(buffer.getContentsAsString());
console.log('>>>> End: ' + line + '<<<<')
};
});
if (last) {
cb(false); // stop reading
} else {
cb();
}
});
check this example, that should help..
var fs = require('fs');
var util = require('util');
var logFile = fs.createWriteStream('log.txt', { flags: 'a' });
// Or 'w' to truncate the file every time the process starts.
var logStdout = process.stdout;
console.log = function () {
logFile.write(util.format.apply(null, arguments) + '\n');
logStdout.write(util.format.apply(null, arguments) + '\n');
}
console.error = console.log;
I am trying to get Strophe.js based XMPP file transfer to work. I can get logged in to work on my openfire server. I can send messages and receive messages fine but I am having trouble with file transfer.
HTML:
<form name='file_form' class="panel-body">
<input type="file" id="file" name="file[]" />
<input type='button' id='btnSendFile' value='sendFile' />
<output id="list"></output>
</form>
Javascript file:
// file
var sid = null;
var chunksize;
var data;
var file = null;
var aFileParts, mimeFile, fileName;
function sendFileClick() {
file =$("#file")[0].files[0];
sendFile(file);
readAll(file, function(data) {
log("handleFileSelect:");
log(" >data="+data);
log(" >data.len="+data.length);
});
}
function sendFile(file) {
var to = $('#to').get(0).value;
var filename = file.name;
var filesize = file.size;
var mime = file.type;
chunksize = filesize;
sid = connection._proto.sid;
log('sendFile: to=' + to);
// send a stream initiation
connection.si_filetransfer.send(to, sid, filename, filesize, mime, function(err) {
fileTransferHandler(file, err);
});
}
function fileTransferHandler(file, err) {
log("fileTransferHandler: err=" + err);
if (err) {
return console.log(err);
}
var to = $('#to').get(0).value;
chunksize = file.size;
chunksize = 20 * 1024;
// successfully initiated the transfer, now open the band
connection.ibb.open(to, sid, chunksize, function(err) {
log("ibb.open: err=" + err);
if (err) {
return console.log(err);
}
readChunks(file, function(data, seq) {
sendData(to, seq, data);
});
});
}
function readAll(file, cb) {
var reader = new FileReader();
// If we use onloadend, we need to check the readyState.
reader.onloadend = function(evt) {
if (evt.target.readyState == FileReader.DONE) { // DONE == 2
cb(evt.target.result);
}
};
reader.readAsDataURL(file);
}
function readChunks(file, callback) {
var fileSize = file.size;
var chunkSize = 20 * 1024; // bytes
var offset = 0;
var block = null;
var seq = 0;
var foo = function(evt) {
if (evt.target.error === null) {
offset += chunkSize; //evt.target.result.length;
seq++;
callback(evt.target.result, seq); // callback for handling read chunk
} else {
console.log("Read error: " + evt.target.error);
return;
}
if (offset >= fileSize) {
console.log("Done reading file");
return;
}
block(offset, chunkSize, file);
}
block = function(_offset, length, _file) {
log("_block: length=" + length + ", _offset=" + _offset);
var r = new FileReader();
var blob = _file.slice(_offset, length + _offset);
r.onload = foo;
r.readAsDataURL(blob);
}
block(offset, chunkSize, file);
}
function sendData(to, seq, data) {
// stream is open, start sending chunks of data
connection.ibb.data(to, sid, seq, data, function(err) {
log("ibb.data: err=" + err);
if (err) {
return console.log(err);
}
// ... repeat calling data
// keep sending until you're ready you've reached the end of the file
connection.ibb.close(to, sid, function(err) {
log("ibb.close: err=" + err);
if (err) {
return console.log(err);
}
// done
});
});
}
$('#btnSendFile').bind('click', function() {
console.log('File clicked:');
sendFileClick();
});
Full code is based on:
Complete example of Strophe.js file transfer
http://plnkr.co/edit/fYpXo1mFRWPxrLlgr123 (source can be download here: has errors). I changed the sendFileClick function.
I am getting:
ibb.open: err=Error: feature-not-implemented? Why is this error I am getting?
I am locally testing my node video upload. my upload class looks like this:
var videoExtensions = ['mp4', 'webm', 'mov'];
var audioExtensions = [];
//Media object
function Media(file, targetDirectory) {
this.file = file;
this.targetDir = targetDirectory;
}
Media.prototype.isVideo = function () {
return this.file.mimetype.indexOf('video') >= 0;
};
Media.prototype.isAudio = function () {
return this.file.mimetype.indexOf('audio') >= 0;
};
Media.prototype.getName = function () {
return this.file.originalname.substr(0, this.file.originalname.indexOf('.'))
};
router.route('/moduleUpload')
.post(function (request, response) {
var media = new Media(request.files.file, '../user_resources/module/' + request.body.module_id + '/');
if (!fs.existsSync(media.targetDir)) {
fs.mkdirSync(media.targetDir, 0777, function (err) {
if (err) {
console.log(err);
response.send("ERROR! Can't make the directory! \n"); // echo the result back
}
});
}
if (media.isVideo()) {
convertVideos(media);
}
else if (media.isAudio()) {
convertAudio(media);
}
else {
moveFile(media);
}
response.status(200).json('user_resources/module/' + request.body.module_id + '/' + media.getName());
});
router.route('/retrieveFile')
.post(function (request, response) {
var path = '../' + request.body.data;
var file = fs.createReadStream(path);
file.pipe(response);
});
function convertVideos(media) {
var ffmpeg = require('fluent-ffmpeg');
videoExtensions.forEach(function (extension) {
var proc = new ffmpeg({source: media.file.path, nolog: false})
.withVideoCodec('libx264')
.withVideoBitrate(800)
.withAudioCodec('libvo_aacenc')
.withAudioBitrate('128k')
.withAudioChannels(2)
.toFormat(extension)
.saveToFile(media.targetDir + media.getName() + '.' + extension,
function (retcode, error) {
console.log('file has been converted succesfully');
});
});
}
function convertAudio(media) {
var ffmpeg = require('fluent-ffmpeg');
audioExtensions.forEach(function (extension) {
var proc = new ffmpeg({source: media.file.path, nolog: false})
.withVideoCodec('libx264')
.withVideoBitrate(800)
.withAudioCodec('libvo_aacenc')
.withAudioBitrate('128k')
.withAudioChannels(2)
.toFormat(extension)
.saveToFile(media.targetDir + media.getName() + '.' + extension,
function (retcode, error) {
console.log('file has been converted succesfully');
});
});
}
When a video file is uploaded it is convert into 3 different files.
Now the file i wish to upload is in my /Video folder at first this did not have any permissions. Which resulted in the upload could not play. However as soon as i changed the permission of the file to 777 the video plays without a problem.
My question is why? am i missing something in my upload and is chmod 777 wise?
also note im using ubuntu 14.04