简体   繁体   English

如何在nodejs中使用fs模块在同一目录中复制和写入文件?

[英]How to copy and write file in the same directory using fs module in nodejs?

trying copy file from directory and writing new file in the same directory using fs module it seems not working not sure what has implemented wrong any help will be apprecaited , once new file is created then i will make changes in new json file is what i am trying to achieve .尝试从目录复制文件并使用fs模块在同一目录中写入新文件它似乎不起作用不确定是什么实现了错误任何帮助都会得到认可,一旦创建新文件然后我将在新的 json 文件中进行更改就是我试图实现。

main.js主文件

     const fs = require("fs");
      async function copyAndCreateNewFile (path, files) {
     
            try {
                let rawdata = fs.readFileSync(files[0]);
                 let parsedJson = JSON.parse(rawdata);
                 console.log("JSON DATA", parsedJson);
                 let data = JSON.stringify(parsedJson);
                const newFile = fs.writeFileSync(`${path}/${"test.json"}`, data);
                return newFile;
            }
            catch(err) {
                console.log ('not able to write data in the file ')
            }
        
      }

copyAndCreateNewFile('dir/services', ['dir/services/fileToCopy.json'])

Error错误

not able to write data in the file  { Error: EACCES: permission denied, open '/test.json'

A simpler way to copy a file in Node:在 Node 中复制文件的更简单方法:

const fs = require('fs');

fs.copyFile('source', 'destination', (err) => {
  console.error(err);
});

Make sure you have write permission to the destination dir.确保您对目标目录具有写权限。
For example:例如:

sudo chmod 777 <destination-dir>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM