首页 > 解决方案 > 我可以通过将代码 NODE.js 放在要从 HTML 调用它的 JS 文件中来创建文件并向其写入值吗?

问题描述

这是从 VSC 终端运行时有效的简单代码。

const fs = require('fs');
const path = require('path');

fs.mkdir(path.join(__dirname, 'json'), err => {
    if (err) {
        throw err;
    }
    console.log('File created');
});

const filePath = path.join(__dirname, 'json', 'temp.txt');

fs.writeFile(filePath, 'Some value', err => {
    if (err) {
        throw err;
    }

    console.log('Value was signed into the file');

});

现在,我将同样的东西放入 JS 文件中,其中有一些计算,我想将结果写入文件。这不起作用。

            project_data = [];
            project_data[0] = parseInt(initial_data);
            for (i=1;  i < len_table; i++) {
                project_data[i] = parseInt(project_data[i-1]) + 1;
            }
            
            const oil_production_map = new Map();
            for (i = 0; i < len_table; i++) {
                oil_production_map.set(project_data[i],parseInt(oil_production[i])); 
            }
        

            const fs = require('fs');
            const path = require('path');
            
            fs.mkdir(path.join(__dirname, 'json'), err => {
                if (err) {
                    throw err;
                }
                alert('File created');
            });
            
            const filePath = path.join(__dirname, 'json', 'oil_production_file.txt');
            
            fs.writeFile(filePath, 'Some value', err => {
                if (err) {
                    throw err;
                }
            
                alert('Value was signed into the file');
            
            });

要求未定义.jpg

标签: node.js

解决方案


推荐阅读