When I run the following code a blank file gets created with the correct name. I clearly dont want a blank file.
I know the path is correct because when i make it purposely incorrect it fails (obviously)
const path = require('path');
const fse = require('fs-extra');
const OUTPUT_PATH = 'js/libs/';
const _NODE_MODULES = 'node_modules/';
const filePath = `${_NODE_MODULES}tooltipster/dist/js/tooltipster.bundle.min.js`;
fse.copy(path.join(__dirname, filePath), path.join(__dirname, `${OUTPUT_PATH}/something.js`), err => {
if (err) {
console.log(err);
process.exit(1)
}
console.log('Copy complete');
process.exit(0);
})
Output of this is
Copy Complete
But the file is blank as I previously stated. Any idea what I'm doing wrong here?
I've modified Your code and checked on my PC.
So result: http://joxi.ru/ZrJEEJh1KXw1Aj
Checkout this code:
const path = require('path');
const fs = require('fs-extra');
let sourceFile = path.join(__dirname, 'node_modules', 'tooltipster/dist/js/tooltipster.bundle.min.js');
let destinationFile = path.join(__dirname, 'js/libs', 'something.js');
fs.copy(sourceFile, destinationFile, err => {
if (err) {
return console.error(err);
}
console.log('Copy complete');
});
if it fail again so, be sure that there is no issue with code.
check Your filesystem maybe there is some open file limits, permission problems or no free space.
also I can guess that the source file is empty, so do:
cat node_modules/tooltipster/dist/js/tooltipster.bundle.min.js
Your call to process.exit interfered/aborted before it could finish. Don't need to call process.exit. It will exit when everything is done.
Related
i have a problem with node.js, i have a script that download from a sftp server some zip file, every zip file are a compress csv file. My task is to download the file, unzip it and delete the zip file.
I have already a working script to download all the files from the sftp server. Now i would like to add to this script a function to unzip all the files and store only the csv files.
For doing that i started to work to a local script that open directly a single file and it had tried to unzip it. But i can't figured out how to do.
This is the portion of code that i wrote, after this code starts working I would like to put it in a helper function class where i can call from my script after the process of the download from sftp was completed.
Anyone can help me to understand on what i am wrong?
const logger = require("./utils/logger");
const path = require("path");
const fs = require("fs");
const unzipper = require("unzipper");
const { LOCAL_IN_DIR_PATH } = require("./utils/consts");
const unzipAll = async (pathToSearch) => {
console.log("unzipAll");
try {
const compFiles = fs.readdirSync(pathToSearch).forEach(function (file) {
if (file.endsWith(".zip")) {
const path = LOCAL_IN_DIR_PATH + `/${file}`;
fs.createReadStream(path).pipe(
unzipper.Extract({ path: path })
);
}
});
} catch (err) {
console.log(err);
}
};
const run = async () => {
try {
const LOCAL_IN_DIR_PATH = path.resolve(__dirname, "IN");
const result = await unzipAll(LOCAL_IN_DIR_PATH);
console.log(result);
} catch (error) {
console.log(error);
}
};
run();
I was trying to watch a certain directory and when a new file is added to that directory I want to rename the file but it's not working. The problem is the directory watching part works fine but when I rename the newly added file the name I am giving it is iterated and giving it the wrong name. For Example, if the new name I'm assigning is thisIsName when it gets renamed it becomes thisIsNamethisIsNamethisIsNamethisIsName. How can I make it so that the rename is the assigned name without any iteration? Any help is appreciated. Thanks in advance.
const fs = require("fs");
const chokidar = require('chokidar');
const watcher = chokidar.watch('filePath', {
ignored: /(^|[\/\\])\../,
persistent: true
});
function yyyymmdd() {
var now = new moment();
return now.format("YYYYMMDD");
}
function hhmmss() {
var now = new moment();
return now.format("HHmmss");
}
const log = console.log.bind(console);
//watching a certain directory for any update to it
watcher
.on('add', path => {
const newFileName = "filePath\\" + yyyymmdd() + hhmmss() + path
//trying to rename the file, but its not working because newFileName is somehow getting looped and having multiple iterations of the DATE and TIME in the new name when getting renamed. Example of what the product looks like is included above in the question.
fs.renameSync(path, newFileName);
})
.on('change', path => {
log(`File ${path} has been changed`)
})
.on('unlink', path => {
log(`File ${path} has been removed`)
})
I've done some small changes in your code and it worked for me for any file formats (for unformatted files as well). Anyway, use as you want. The only thing you've missed, was the usage of "path":
const moment = require('moment');
const fs = require('fs');
const chokidar = require('chokidar');
const path = require('path');
const log = console.log.bind(console);
function formattedDate() {
return moment().format('YYYYMMDDHHmmss');
}
// here I've used some folder with name "folder" in the same directory as this file
const filePath = path.join(__dirname, `./folder`);
const watcher = chokidar.watch(filePath, {
ignored: /(^|[\/\\])\../,
persistent: true
});
watcher
.on('add', addedFilePath => {
const fileExt = path.extname(addedFilePath);
const newFilePath = path.join(__dirname, `./folder/${formattedDate()}${fileExt}`);
fs.renameSync(addedFilePath, newFilePath);
})
.on('change', changedFilePath => {
log(`File ${changedFilePath} has been changed`);
})
.on('unlink', removingFilePath => {
log(`File ${removingFilePath} has been removed`);
});
Here is the stuff:
csv file is
and in my index.js
here is my code :
const fs = require('fs');
const csv = require('csv-parser');
const inputFile = "./data.csv"
let results = []
fs.createReadStream(inputFile)
.pipe(csv())
.on('data', (data) => results.push(data))
.on('end', () => {
console.log(results);
});
why am i getting an error: that no such file or directory './data.csv'?
When specifying file paths in node, generally relative paths are derived from the working directory from where node itself was executed. This means if you execute
node ./backEnd/index.js
The actual working directory is whatever directory is above backEnd. You can see this via console.log(process.cwd()).
If you would like to read a file relative to the current file that is being executed, you can do:
const fs = require('fs');
const path = require('path');
const csv = require('csv-parser');
const inputFile = path.resolve(__dirname, "./data.csv");
let results = []
fs.createReadStream(inputFile)
.pipe(csv())
.on('data', (data) => results.push(data))
.on('end', () => {
console.log(results);
});
Specifically __dirname will always resolve to the directory of the javascript file being executed. Using path.resolve is technically optional here, you could manually put the path together, however using resolve is a better practice.
I have tried with this code but it's not working it display error like that file not exists on that directory.
System take .txt as file not as extension of file.
const fs = require('fs');
var oldPath = '/abc/def/ghi/*.txt'
var newPath = '/xyz/cbi/'
fs.rename(oldPath, newPath, function (err) {
if (err) throw err
console.log('Successfully renamed - AKA moved!')
})
Try this one:
const shell = require('child_process').execSync ;
const src= `/abc/def/ghi`;
const dist= `/xyz/cbi`;
shell(`mv ${src}/* ${dist}`);
This will solve your problem Check here
const fs = require('fs-extra')
// With a callback:
fs.copy('/tmp/myfile', '/tmp/mynewfile', err => {
if (err) return console.error(err)
console.log('success!')
})
Try this one
For One File:
const moveThem = async () => {
// Move file ./js/foo.js to ./ns/qux.js
const original = join(__dirname, 'js/foo.js');
const target = join(__dirname, 'ns/qux.js');
await mv(original, target);
}
For Many Files:
mv('source/dir', 'dest/a/b/c/dir', {mkdirp: true}, function(err) {
});
OR
var spawn = require('child_process').spawn,
mv = spawn('mv', ['/dir1/dir2/*','dir1/']);
For some reason when I try to write a file on my localhost (windows 7) the writestream won't open. On a linux machine, it works fine. Is there some type of permissions I need to add in windows?
I'm already running as administrator.
Here is the current method.
// Mainfunction to recieve and process the file upload data asynchronously
var uploadFile = function(req, targetdir,callback) {
var total_uploaded = 0
,total_file;
// Moves the uploaded file from temp directory to it's destination
// and calls the callback with the JSON-data that could be returned.
var moveToDestination = function(sourcefile, targetfile) {
moveFile(sourcefile, targetfile, function(err) {
if(!err)
callback({success: true});
else
callback({success: false, error: err});
});
};
// Direct async xhr stream data upload, yeah baby.
if(req.xhr) {
var fname = req.header('x-file-name');
// Be sure you can write to '/tmp/'
var tmpfile = '/tmp/'+uuid.v1();
total_file = req.header('content-length');
// Open a temporary writestream
var ws = fs.createWriteStream(tmpfile);
ws.on('error', function(err) {
console.log("uploadFile() - req.xhr - could not open writestream.");
callback({success: false, error: "Sorry, could not open writestream."});
});
ws.on('close', function(err) {
moveToDestination(tmpfile, targetdir+fname);
});
// Writing filedata into writestream
req.on('data', function(data,t,s) {
ws.write(data,'binary',function(r,e){
total_uploaded = total_uploaded+e;
var feed = {user:'hitesh',file:fname,progress:(total_uploaded/total_file)*100};
require('./../../redis').broadCast(JSON.stringify(feed))
});
});
req.on('end', function() {
ws.end();
});
}
// Old form-based upload
else {
moveToDestination(req.files.qqfile.path, targetdir+req.files.qqfile.name);
}
};
As your code is running fine on Linux it must be something specific to Windows.
var tmpfile = '/tmp/'+uuid.v1();
might be your problem. The folder/path structure on windows is different. Try using the path module and change your code to
var path = require('path');
var tmpfile = path.join('tmp', uuid.v1());
The same goes probably to your parameter targetdir.
see this related question.
The problem is with the directory. Unless you have a C:\tmp directory (assuming you're running node from the C drive), it doesn't have anywhere to write the tmp file.
You could either create a C:\tmp directory or modify the line
var tmpfile = '/tmp/'+uuid.v1();
to something like
var tmpfile = __dirname + '/tmp/'+ uuid.v1();
Note: requires a directory something like C:\mynodeproject\tmp