'How to copy a file in node.js?
I'm learning Node.js and using the Hyper Terminal and Visual Studio Code.
I want to copy a file through Hyper Terminal and notice that const fs = require("fs"); doesn't work in CommonJS.
So I try to use the import like it says in Node.js docs.
This is the code:
import * as fs from 'fs';
fs.copyFile("file1.txt", "file2.txt", messageFunction);
function messageFunction() {
console.log("file 1 was copied");
}
This is what it shows on the Hyper Terminal:
Catarina@DESKTOP-3FEBJ01 MINGW64 ~/Desktop/HTML.CSS.JAVASCRIPT/intro-to-node
$ node index.js
file 1 was copied
The problem is that does not create a new file, it simply shows the console.log.
I also create a package.json and add "type" : "module".
Thank you!
Solution 1:[1]
So, after 2 days I found the solution... I wrote on the paste file1.text instead of file1.txt.
But I learnt that if you use import with the callback function you have to change the package.json to "type" : "module", and if you use the const with the return you need to also change the package.json to "type": "commonjs".
Hope it helps other people! Thank you :)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | catarinasoares |
