A
A
Adik Izat2019-10-10 18:56:42
Node.js
Adik Izat, 2019-10-10 18:56:42

What is the correct way to create a new file in NodeJS?

let date = new Date();
    let filename = SSN + '_' + date.getFullYear() + '/' + date.getMonth() + '/' + date.getDay() + '_' + date.getHours() + ':' + date.getMinutes() + ':' + date.getSeconds() + '.txt';
    let text = '';
    ecg.forEach((item) => {
        text += item;
    });
    try{
        fs.writeFileSync(filename, text);
    } catch (e) {
        console.log(e);
    }

Good evening forum users! I’m not very close with NodeJS, but that’s the thing, I’m trying to create a new file with the text I need, but I can’t do it right, I always get the following error:
Error: ENOENT: no such file or directory, open '980524420063_2019/9/4_21:49:15.txt'
    at Object.openSync (fs.js:448:3)
    at Object.writeFileSync (fs.js:1248:35)
    at Timeout.logECG [as _onTimeout] (C:\Users\adeke\Desktop\comCatcher\index.js:32:12)
    at listOnTimeout (internal/timers.js:531:17)
    at processTimers (internal/timers.js:475:7) {
  errno: -4058,
  syscall: 'open',
  code: 'ENOENT',
  path: '980524420063_2019/9/4_21:49:15.txt'
}

Please help! Thanks everyone!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
Roman, 2019-10-10
@JaxAdam

first create the directories in which this file is located
if the version of the node is greater than 10.12.00 then try this

function saveFileSync(path, data){
  let list = path.split(/[\\\/]/);
  let filename = list.pop();
  let filepath = list.join('/');
  fs.mkdirSync(filepath, { recursive: true }, (err) => {
    if (err) throw err;
  });
  fs.writeFileSync(path, data);
}



let date = new Date();
let filename = SSN + '_' + date.getFullYear() + '/' + date.getMonth() + '/' + date.getDay() + '_' + date.getHours() + ':' + date.getMinutes() + ':' + date.getSeconds() + '.txt';
let text = ecg.join('');
try{
    saveFileSync(filename, text);
} catch (e) {
    console.log(e);
}

A
Adik Izat, 2019-10-10
@JaxAdam

This is not a slash!

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question