Copy a source file to another destination in Nodejs - javascript

I'm trying to copy an image from a folder to another using fs-extra module .
var fse = require('fs-extra');
function copyimage() {
fse.copy('mainisp.jpg', './test', function (err) {
if (err)
return console.error(err)
});
}
This is my directory
and this is the error I get all the time:
Error {errno: -4058, code: "ENOENT", syscall: "lstat", path:
"E:\mainisp.jpg", message: "ENOENT: no such file or directory, lstat
'E:\mainisp.jpg'"}
and by changing destination to ./test/ I get this error
Error {errno: -4058, code: "ENOENT", syscall: "lstat", path:
"E:\Development\Node apps\Node softwares\Digital_library\mainisp.jpg",
message: "ENOENT: no such file or directory, lstat 'E:\Devel…
apps\Node softwares\Digital_library\mainisp.jpg'"}
Note: I'm not testing this in browser. It's an Nwjs app and the pics of error attached are from Nwjs console.

You can do this using the native fs module easily using streams.
const fs = require('fs');
const path = require('path');
let filename = 'mainisp.jpg';
let src = path.join(__dirname, filename);
let destDir = path.join(__dirname, 'test');
fs.access(destDir, (err) => {
if(err)
fs.mkdirSync(destDir);
copyFile(src, path.join(destDir, filename));
});
function copyFile(src, dest) {
let readStream = fs.createReadStream(src);
readStream.once('error', (err) => {
console.log(err);
});
readStream.once('end', () => {
console.log('done copying');
});
readStream.pipe(fs.createWriteStream(dest));
}

Try:
var fs = require('fs-extra');
fs.copySync(path.resolve(__dirname,'./mainisp.jpg'), './test/mainisp.jpg');
As you can see in the error message, you're trying to read the file from E:\mainisp.jpg instead of the current directory.
You also need to specify the target path with the file, not only the destination folder.

Try:
const fs = require('fs');
fs.copyFileSync(src, dest);

Related

directory is not creating

Am trying to create a directory with subfolders in my application. The new request will create folders only if the parent folder is already there but not creating if root folder is not there.
import { mkdir } from 'fs';
mkdir(join(__dirname, '../folder_to_create_directory/', req.body.path), (err) => {
if (err) {
return "error";
}
return "success"
});
The req.body.path is a path string eg: test/folder/subfolder. The code will work only if we create the "test" folder manually (it is not returning "success" message too even though the directory is being created). IF the test folder is not there then the directory is not creating.
expected output:-
folder_to_create_directory/test/folder/subfolder
You can use fs library to work with a file system.
For nested dirs:
var fs = require('fs');
var dir = join(__dirname, '../folder_to_create_directory/', req.body.path);
if (!fs.existsSync(dir)){
fs.mkdirSync(dir, { recursive: true });
}
Or, for individual dirs:
var fs = require('fs');
var dir = join(__dirname, '../folder_to_create_directory/', req.body.path);
if (!fs.existsSync(dir)){
fs.mkdirSync(dir);
}
you are missing an option "{recursive: true}". Try this example:
const { mkdir } = require("fs");
const {join} = require('path')
const path = join(__dirname, "../folder_to_create_directory", 'test/folder/subfolder')
mkdir(path, { recursive: true }, (err) => {
if (err) {
return "error";
}
return "success";
});

How to get files list using fileSystem?

I am trying to get list of files in specified directory but its throwing error any idea what is implemented wrong in below code.
service.js
var fs = require('fs');
var path = require('path');
var async = require('async');
var filePath = path.resolve('./logs/dit/');
function checkSearchObj () {
fs.readdir(filePath,function (err, files) {
files.forEach(function(file) {
console.log(file);
});
})
}
checkSearchObj();
error
TypeError: Cannot read property 'forEach' of undefined
at C:\Users\sh529u\WebstormProjects\ulog\app\serverf
s:8:15
at FSReqWrap.oncomplete (fs.js:82:15)
Change this:
function checkSearchObj () {
fs.readdir(filePath,function (err, files) {
files.forEach(function(file) {
console.log(file);
});
})
}
to this:
function checkSearchObj () {
fs.readdir(filePath,function (err, files) {
if (err) {
console.log('Error:', err);
return;
}
files.forEach(function(file) {
console.log(file);
});
})
}
to see what's the error.
You need to check for errors instead of assuming that there was no error or otherwise you will try to access undefined variables and the only error you'll see is that you access undefined and not the actual error that's in err in this case.
Your callback will either get the err or the files but not both.
Update:
After changing the code to display error you got:
Error: { [Error: ENOENT: no such file or directory, scandir 'C:\Users\Web stormProjects\ulog\app\serverfiles\logs\dit'] errno: -4058, code: 'ENOENT', syscall: 'scandir', path: 'C:\\Users\\sh529u\\WebstormProjects\\ulog\\app\\serverfiles‌​\\logs\\dit'
Which means that the program doesn't display the files in the directory because there is no such directory. Mystery solved. Now you can see how useful it is to actually check the errors.

fs.readFileSync Error

I am trying to use the html-pdf node module to generate pdfs from html. I am currently running this using the cloud9 IDE.
My code is:
var fs = require("fs");
var pdf = require('html-pdf');
var html = fs.readFileSync('./test.html', {encoding: 'utf8'});
var options = { format: 'Letter' };
app.post('/pdf',function(req, res) {
pdf.create(html, options).toFile('./businesscard.pdf', function(err, res) {
if (err) return console.log(err);
console.log(res); // { filename: '/app/businesscard.pdf' }
});
});
I get the following Error:
[Error: Fontconfig warning: ignoring C.UTF-8: not a valid language tag]
Does anyone know how i can resolve this issue?
This is due to a bug in fontconfig. You can see here
Open your terminal and execute locale -a you will see list of fonts. Then select it like LC_ALL=C
may it can help

Get local json file using request-promise

I'm making a node/express app and am querying a test json file using npm request-promise. Node is spitting out the following error in my <title> tags:
Error: <title>Invalid URI "../testJSON/user.json"</title>
I believe my pathing is correct, so am unsure why it's an invalid URI.
I've also provided the entire project path URI with the same issue:
return rp('http://localhost:3000/app/testJSON/user.json');
User Service:
module.exports = {
getUserData: function(){
var options = {
uri : '../testJSON/user.json',
method : 'GET'
}
return rp(options);
}
}
User Controller:
var User = require('../services/User.service');
User.getUserData()
.then(function(data){
res.render('pages/userdata', {
title: 'User Data',
content: JSON.parse(data)
});
})
.catch(function(err){
console.log(err);
});
Pathing:
User Service: projectroot/app/services/userService.js
User json file: projectroot/app/testJSON/user.json
Update: trying with node fs to fetch local file
fs = require('fs');
module.exports.index = function (req, res) {
fs.readFile('../testJSON/user.json', 'utf8', function (err,data) {
if (err) {
return console.log(err);
}
res.render('pages/user', {
title: 'User',
content: JSON.parse(data)
});
});
...
Node error:
{ [Error: ENOENT, open '../testJSON/user.json'] errno: -2, code:
'ENOENT', path: '../testJSON/user.json' }
Relative paths (starting with ../ or ./) are relative to the current working directory. If you want to read a file relative to the current JS source file, you need to prefix the path with __dirname, which is the directory where the current JS source file resides:
fs.readFile(__dirname + '/../testJSON/user.json', ...);
Or the more elaborate (but probably more correct) way:
var path = require('path);
...
fs.readFile(path.join(__dirname, '../testJSON/user.json'), ...);

nodejs load file

I want to load test.txt with nodejs.
var fs = require('fs');
fs.readFile('./test.txt', function (err, data) {
if (err) {
throw err;
}
console.log(data);
});
The path of the server is C:\server\test\server.js. The test.txt is located in the same directory, but I get this error: Error: ENOENT, no such file or directory 'C:\Users\User\test.txt'
Paths in Node are resolved relatively to the current working directory. Prefix your path with __dirname to resolve the path to the location of your Node script.
var fs = require('fs');
fs.readFile( __dirname + '/test.txt', function (err, data) {
if (err) {
throw err;
}
console.log(data.toString());
});
With Node 0.12, it's possible to do this synchronously now:
var fs = require('fs');
var path = require('path');
// Buffer mydata
var BUFFER = bufferFile('../test.txt');
function bufferFile(relPath) {
return fs.readFileSync(path.join(__dirname, relPath)); // zzzz....
}
fs is the file system. readFileSync() returns a Buffer, or string if you ask.
fs correctly assumes relative paths are a security issue. path is a work-around.
To load as a string, specify the encoding:
return fs.readFileSync(path,{ encoding: 'utf8' });
You should use __dirname to get the directory name the file is located instead of the current working directory:
fs.readFile(__dirname + "/test.txt", ...);
Use path and fs:
const fs = require("fs");
const pth = require("path");
Sync:
let data = fs.readFileSync(pth.join(__dirname,"file.txt"));
console.log(data + "");
A-Sync:
fs.readFile(pth.join(__dirname,"file.txt"), (err, data) => {
console.log(data + "");
});
And that; If you need to read the file continuously and send it to the client and the file size is not large, you may be able to keep a copy of it:
const exp = require("express");
const app = exp();
const fs = require("fs");
const pth = require("path");
let file = "";
app.get("/file", (q, r) => {
if (file === "")
file = fs.readFileSync(pth.join(__dirname,"file.txt")) + "";
r.writeHead(200, { "Content-Type": "text/plain" });
r.write(file);
r.end();
});
so if it is in the same directory just do this
fs.readFile(__dirname+'/foo.txt',function(e,d){console.log(d)})
If it's in same directory it should work. I have tested with the same code, with a file name.txt and it's working fine:
var fs = require('fs');
fs.readFile('./test.txt', function (err, data) {
if (err) {
throw err;
}
console.log(data.toString());
});

Categories