Node.js script to copy files overwriting previous ones? - node.js

I wish to create a Node.js script to copy files overwriting previous versions of the same files.
My code doesn't work:
const fs = require('fs');
var src = "srcPath/file.json";
var newPath = "newPath/file.json";
var callback = (result) => {
console.log(result);
}
copy(src, newPath, callback);
function copy(src, newPath, callback){
fs.copyFile(src, newPath, (err) => {
if (err) {
callback("Error Found:", err);
}
else {
callback("Success: "+newPath);
}
});
}
execute()

It will work, if you take this line off:
execute()

Related

Only few files being extracted using node.js unzip modules

I've been using Unzip library in NodeJS, however, only few files are being extracted, and on each execution the files extracted are different
fs.createReadStream('test.zip').pipe(unzipper.Extract({ path: 'test' })
.on('finish', function() {
console.log("finish")
})
To fix the above issue, I had to implement the below instead of the code posted in the question
fs.createReadStream("test.zip").on("error", log).pipe(unzipper.Parse()).on("entry", function (entry) {
var isDir = entry.type === "Directory";
var fullpath = path.join(dest, entry.path);
// console.log("fullpath ", fullpath)
var directory = isDir ? fullpath : path.dirname(fullpath);
mkdirp(directory, function (err) {
if (err)
throw err;
if (!isDir) {
entry.pipe(fs.createWriteStream(fullpath));
}
})
.on("close", function (message) {
console.log("close");
resolve("/DEST")
}).on("finish", function (message) {
console.log("finish");
resolve("/DEST")
});
});

how to add new line using fs.writeFile?

I tried to write my project's files to a new file, each one in new line, using Node.js. How can I do that? Below is my code:
var fs = require('fs');
var colors = require('colors');
fs.readdir('./', 'utf-8', function(err, data) {
if (err) throw err;
console.log(data);
fs.writeFile('./new.txt', data, function(err) {
if (err) throw err;
console.log('Saved!'.blue);
});
});
You can collect all filenames first and then write them to a file.
const fs = require('fs');
const colors = require('colors');
let fileNames = '';
fs.readdir('./', 'utf-8', function(err, data) {
data.forEach(filename => fileNames += filename + '\n');
fs.writeFile('./new.txt', fileNames, function(err) {
if (err) throw err;
console.log('Saved!'.blue);
});
});

cannot pass learnyounode: is the callback function used uncorrectly?

I am trying to solve the sixth problem of learnyounode which needs a module file to print file list. Here are my two files:
The main file program.js:
var mymodule = require('./module.js');
mymodule(process.argv[2], process.argv[3], function(err, file){
if(err){
console.log(err);
return;
}
console.log(file);
});
The module file module.js:
var fs = require('fs');
var path = require('path');
var fileExt;
module.exports = function(dir, ext, callback) {
fs.readdir(dir, function(err, files){
if(err){
callback(err);
return;
}
files.forEach(function(file){
fileExt = path.extname(file).substring(1);
if(fileExt === ext){
callback(null, file);
}
});
});
}
But it throws an error:
processors[i].call(self, mode, function (err, pass) {
TypeError: Cannot read property 'call' of undefined
What am I doing wrong?
The instructions state that you need to call callback only once, with an array containing of all the matching files. In your case, you are calling callback once for every matching file.

Reading a .txt file with NodeJS using FS

I'm trying to use NodeJS to read a txt file by using fs. This is the code of app.js:
var fs = require('fs');
function read(file) {
return fs.readFile(file, 'utf8', function(err, data) {
if (err) {
console.log(err);
}
return data;
});
}
var output = read('file.txt');
console.log(output);
When i do:
node app.js
It says
undefined
I have fs installed and there is a file.txt in the same directory, why is it not working?
Your read function is returning the result of the fs.readFile function, which is undefined because it doesn't have a return clause (it uses callbacks). Your second return clause is in an anonymous function, so it only returns to that scope. Anyhow, your function knows its finished after that first return.
The standard way to use fs.readFile is to use callbacks.
var fs = require('fs');
function read(file, callback) {
fs.readFile(file, 'utf8', function(err, data) {
if (err) {
console.log(err);
}
callback(data);
});
}
var output = read('file.txt', function(data) {
console.log(data);
});

Move File in ExpressJS/NodeJS

I'm trying to move uploaded file from /tmp to home directory using NodeJS/ExpressJS:
fs.rename('/tmp/xxxxx', '/home/user/xxxxx', function(err){
if (err) res.json(err);
console.log('done renaming');
});
But it didn't work and no error encountered. But when new path is also in /tmp, that will work.
Im using Ubuntu, home is in different partition. Any fix?
Thanks
Yes, fs.rename does not move file between two different disks/partitions. This is the correct behaviour. fs.rename provides identical functionality to rename(2) in linux.
Read the related issue posted here.
To get what you want, you would have to do something like this:
var source = fs.createReadStream('/path/to/source');
var dest = fs.createWriteStream('/path/to/dest');
source.pipe(dest);
source.on('end', function() { /* copied */ });
source.on('error', function(err) { /* error */ });
Another way is to use fs.writeFile. fs.unlink in callback will remove the temp file from tmp directory.
var oldPath = req.files.file.path;
var newPath = ...;
fs.readFile(oldPath , function(err, data) {
fs.writeFile(newPath, data, function(err) {
fs.unlink(oldPath, function(){
if(err) throw err;
res.send("File uploaded to: " + newPath);
});
});
});
Updated ES6 solution ready to use with promises and async/await:
function moveFile(from, to) {
const source = fs.createReadStream(from);
const dest = fs.createWriteStream(to);
return new Promise((resolve, reject) => {
source.on('end', resolve);
source.on('error', reject);
source.pipe(dest);
});
}
This example taken from: Node.js in Action
A move() function that renames, if possible, or falls back to copying
var fs = require('fs');
module.exports = function move (oldPath, newPath, callback) {
fs.rename(oldPath, newPath, function (err) {
if (err) {
if (err.code === 'EXDEV') {
copy();
} else {
callback(err);
}
return;
}
callback();
});
function copy () {
var readStream = fs.createReadStream(oldPath);
var writeStream = fs.createWriteStream(newPath);
readStream.on('error', callback);
writeStream.on('error', callback);
readStream.on('close', function () {
fs.unlink(oldPath, callback);
});
readStream.pipe(writeStream);
}
}

Resources